In my controller I have two endpoints where one is secured and one is public:
@GetMapping("/public")
public String getPublic() {
return "public";
}
@PreAuthorize("hasRole('USER')")
@GetMapping("/private")
public String getPrivate() {
return "public";
}
Secured endpoint works only when I am logged and token with right role is placed in request header. But when I want access to public endpoint without token I always got status 401 with error
Full authentication is required to access this resource
Here is my security configuration:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests().anyRequest().authenticated()
.and()
.csrf().disable();
}
}
and authorization server config:
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
private final UserDetailsService appUserDetailService;
private final AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints
.tokenStore(tokenStore())
.tokenEnhancer(tokenEnhancer())
.authenticationManager(authenticationManager)
.userDetailsService(appUserDetailService);
}
}
I also tried change .authorizeRequests().anyRequest().authenticated()
to this : .authorizeRequests().anyRequest().permitAll()
with no change. My preferred way is handle security with annotations. Thank you.