I have two REST endpoints:
/noAuth/rest/sayHi
/rest/auth/getMsg
I want to give login for only /rest/auth/getMsg
and direct access to /noAuth/rest/sayHi
.
When I am using below pattern in WebSecurityConfigurerAdapter.configure(HttpSecurity http)
@EnableWebSecurity
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("Java Techie")
.password("Password")
.roles("ADMIN");
auth
.inMemoryAuthentication()
.withUser("Basant")
.password("Password2")
.roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/rest/**").authenticated()
.anyRequest().permitAll()
.and()
.httpBasic();}
}
}
I only get login prompt in /rest/auth/getMsg
but not in /noAuth/rest/sayHi
, which is as expected.
But when I use below pattern, I get login prompt in both /rest/auth/getMsg
and /noAuth/rest/sayHi
which is quite unexpected for me.
http
.authorizeRequests()
.anyRequest().authenticated()
.antMatchers("/rest/**").permitAll()
.and()
.httpBasic();`
I know for IInd time I am doing something wrong, so I want to understand why I am not getting login for only /rest/auth/getMsg
and direct access to /noAuth/rest/sayHi
.
Update
@nully It makes some sense but breaks my understanding for other case. Lets say if I use this pattern:
http
.authorizeRequests()
.anyRequest().authenticated()
.anyRequest().hasRole("ADMIN")
.and()
.httpBasic();`
allows only user = "Java Techie " to login since it is an ADMIN
and throws 403 Forbidden
for user = "Basant".
But when I use
http
.authorizeRequests()
.anyRequest().authenticated()
.antMatchers("/rest/**").hasRole("ADMIN")
.and()
.httpBasic();
from your explanation it should not allow user = "Basant" to access /rest/auth/getMsg
since it has role = "USER"
. But actually it is allowing me to access /rest/auth/getMsg
when I use user = "Basant".