I am setting up a standalone OAuth2 Resource Server and it does not appear to be authenticating requests, using CURL calls without a bearer token seem to succeed anyway. Alternatively, I tried to set up Global Method Security and all requests get rejected with the error
An authentication object could not be found in the current security context
even if @PreAuthorize('submitAll()')
is set on the request in question. I'm happy to take either path to getting authentication to work (method level security or a correct configuration that will inspect tokens).
Here is the code.
@Configuration
@EnableResourceServer
@EnableWebSecurity
class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Bean
public ResourceServerTokenServices tokenService() {
RemoteTokenServices tokenServices = new RemoteTokenServices();
tokenServices.setClientId("commsuite");
tokenServices.setClientSecret("secret");
tokenServices.setCheckTokenEndpointUrl("http://localhost:10386/oauth/check_token");
return tokenServices;
}
@Bean
public AuthenticationManager authenticationManager() {
final OAuth2AuthenticationManager oAuth2AuthenticationManager = new OAuth2AuthenticationManager();
oAuth2AuthenticationManager.setTokenServices(tokenService());
return oAuth2AuthenticationManager;
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenServices(tokenService()).authenticationManager(authenticationManager());
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/2/**").authorizeRequests().anyRequest().authenticated();
}
}
/* Here is the api controller code with the call */
@RequestMapping(value="/test", method = RequestMethod.GET, produces = {"text/plain"})
@ResponseStatus(HttpStatus.OK)
public @ResponseBody
String testEndpoint() {
return "Gnarly Dudes\n";
}
In this case, a raw curl call with no bearer token succeeds.
As a second case, I tried using Method Level security annotations by adding the following code and then adding @PreAuthorize("permitAll()")
to the testEndpoint
method above. In this case, I get the Authentication object could not be found
error both in a raw CURL call and also using a call with a valid bearer token obtained from a separate authentication server. I suspect I'm missing something along the line. Thanks...
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
return new OAuth2MethodSecurityExpressionHandler();
}
}