I want to use OAuth2 for my spring REST download project. Using some examples, I created a configuration for OAuth2:
@Configuration public class OAuth2Configuration { private static final String RESOURCE_ID = "restservice"; @Configuration @EnableResourceServer protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { @Override public void configure(ResourceServerSecurityConfigurer resources) {
This is my SecurityConfiguration class:
@Configuration @EnableWebSecurity @Order(1) public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http .authorizeRequests().antMatchers("/api/register").permitAll() .and() .authorizeRequests().antMatchers("/api/free").permitAll() .and() .authorizeRequests().antMatchers("/oauth/token").permitAll() .and() .authorizeRequests().antMatchers("/api/secured").hasRole("USER") .and() .authorizeRequests().anyRequest().authenticated(); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
I tried to test my application with two simple queries:
@RequestMapping(value = "/api/secured", method = RequestMethod.GET) public String checkSecured(){ return "Authorization is ok"; } @RequestMapping(value = "/api/free", method = RequestMethod.GET) public String checkFree(){ return "Free from authorization"; }
First I checked two queries:
/ api / free code returned 200 and the line "Free from authorization"
/ api / secure returned {"timestamp": 1487451065106, "status": 403, "error": "Forbidden", "message": "Access Denied", "path": "/ API / secured"}
And it seems that they are working fine.
Then I got access_token (using credentials from my users database)
/ OAuth / token grant_type = password &? Username = emaila & password = emailo
Answer:
{"access_token": "3344669f-C66c-4161-9516-d7e2f31a32e8", "token_type": "media", "refresh_token": "c71c17e4-45ba-458c-9d98-574de33d1859", "expires_in": 1199, "scope : "read write"}
Then I tried to send a request (with the token I received) for a resource that requires authentication:
/ Api / secured? Access_token = 3344669f-C66c-4161-9516-d7e2f31a32e8
Here's the answer:
{"timestamp": 1487451630224, "status": 403, "error": "Forbidden", "message": "Access Denied", "path": "/ api / secure"}
I canβt understand why access is denied. I am not sure about the settings, and it seems that they are wrong. Also, I still do not clearly understand the relationship of configure methods (HttpSecurity http) in a class that extends WebSecurityConfigurerAdapter , and in another extends ResourceServerConfigurerAdapter . Thanks for any help!