Spring Oauth2 Resource Server Configuration

I am trying to configure separate auth and resource servers for oauth2. I can configure the authorization server successfully and the ability to authenticate and generate access tokens. Now I want to configure a resource server that can talk to the auth server with the api endpoint to check access tokens. The following is the configuration of my resource server.

@Configuration @EnableResourceServer @EnableWebSecurity public class Oauth2SecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { System.out.println("Oauth2SecurityConfiguration before"); http .authorizeRequests() .antMatchers(HttpMethod.GET, "/api/v1/**").authenticated(); System.out.println("Oauth2SecurityConfiguration after"); } @Bean public AccessTokenConverter accessTokenConverter() { return new DefaultAccessTokenConverter(); } @Bean public RemoteTokenServices remoteTokenServices() { final RemoteTokenServices remoteTokenServices = new RemoteTokenServices(); remoteTokenServices.setCheckTokenEndpointUrl("http://localhost:9000/authserver/oauth/check_token"); remoteTokenServices.setClientId("clientId"); remoteTokenServices.setClientSecret("clientSecret"); remoteTokenServices.setAccessTokenConverter(accessTokenConverter()); return remoteTokenServices; } @Override @Bean public AuthenticationManager authenticationManager() throws Exception { OAuth2AuthenticationManager authenticationManager = new OAuth2AuthenticationManager(); authenticationManager.setTokenServices(remoteTokenServices()); return authenticationManager; } } @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http.csrf().disable(); System.out.println("http.csrf().disable()"); http.authorizeRequests().antMatchers(HttpMethod.GET, "/api/v1/**").fullyAuthenticated(); System.out.println("http.authorizeRequests().anyRequest().authenticated()"); } } @Configuration @EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true) public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration { @Override protected MethodSecurityExpressionHandler createExpressionHandler() { return new OAuth2MethodSecurityExpressionHandler(); } } 

Question: 1. Why am I AuthenticationManager on the resource server while all authentication is delegated to the auth server. (I had to add it to download the application context)

Other than that, I ran into problems below.

  • Despite the fact that I do not pass the authority headers and the access token with the request. It happens.

     http GET "http://localhost:8080/DataPlatform/api/v1/123sw/members" HTTP/1.1 200 OK Content-Type: application/json;charset=UTF-8 Date: Mon, 19 Oct 2015 19:45:14 GMT Server: Apache-Coyote/1.1 Transfer-Encoding: chunked { "entities": [], "errors": [], "message": null } 
  • Filters are called immediately; I do not see the logs for the following queries. Does it cache authorization somewhere?

I am new to spring oauth Please let me know if I am doing something wrong. I use

 spring-security-oauth2 : 2.0.7.RELEASE spring-security-core : 4.0.1.RELEASE java : 1.8 
+5
source share
2 answers

The main thing is to make separate endpoints for the auth server and resource-server so that they can serve them separately, each of them. As shown below, "/ user / getEmployeesListRole / **" -access through the auth server, "/ user / getEmployeesListOAuth2 / **" is access through the resource server using the token generated by the aouth2 server. Also note that auth-server and oauth2-server have the same auth manager

Configuring Spring-boot aouth2-server, resource-server, auth-server in a single spring-boot application

1. Entry point:

 /*AuthApplication.java*/
     @SpringBootApplication
     @EnableDiscoveryClient
     @EnableGlobalMethodSecurity (prePostEnabled = true)
     public class AuthApplication {
     public static void main (String [] args) {
           SpringApplication.run (AuthApplication.class, args);
     }} 
2. Configuration of aouth2 server:
 /*OAuth2AuthorizationConfig.java*/
      @Configuration
      @EnableAuthorizationServer
      public class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter { 
private TokenStore tokenStore = new InMemoryTokenStore ();
@Autowired @Qualifier ("authenticationManagerBean") private AuthenticationManager authenticationManager;
@Autowired @Qualifier ("userDetailsServiceBean") private UserDetailsService userDetailsService;
@Override public void configure (ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory () .withClient ("browser") .authorizedGrantTypes ("password", "refresh_token") .scopes ("ui", "read: ui", "write: ui"); }

@Override public void configure (AuthorizationServerEndpointsConfigurer endpoints) throws an exception {endpoints.tokenStore (tokenStore) .authenticationManager (authenticationManager) .userDetailsService (userDetailsService);
@Override public void configure (AuthorizationServerSecurityConfigurer oauthServer) {oauthServer.tokenKeyAccess("allowAll()").checkTokenAccess("isAuthenticated()").passwordEncoder(NoOpPasswordEncost.In;
@Override public void configure (AuthorizationServerSecurityConfigurer oauthServer) {oauthServer.tokenKeyAccess("allowAll()").checkTokenAccess("isAuthenticated()").passwordEncoder(NoOpPasswordEncost.In;

2.1 aouth2-server authentication request [basic authentication message]:
 http://localhost:5000/uaa/oauth/token?grant_type=password&scope=ui write:ui&username=user&password=123456&client_id=browser 
3. Configuring the resource server:
 /*ResourceServer.java*/
     @Configuration
        @EnableResourceServer
        class ResourceServer extends ResourceServerConfigurerAdapter {
          // Here we specify to allow the request to the 
          // url / user / getEmployeesList with valid access token and scope read
          @Override
          public void configure (HttpSecurity http) throws Exception {
              http.requestMatchers ()
                    .antMatchers ("/ user / getEmployeesList / ** ")
                    .antMatchers ("/ user / getEmployeesListOAuth2 / ** ")
            .and (). authorizeRequests (). anyRequest (). access ("# oauth2.hasScope ('ui')"); 
}}
4. Config auth server:
 /*WebSecurityConfig.java*/
     @Configuration
     @EnableWebSecurity
     public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/resources/**"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/user/getEmployeesListRole/**").access("hasAuthority('WRITE_DATA') && hasAuthority('READ_DATA')").anyRequest().permitAll().and().formLogin().permitAll().and().logout().permitAll().and().csrf().disable(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("admin").password("admin").authorities("WRITE_DATA", "READ_DATA"); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override @Bean public UserDetailsService userDetailsServiceBean() throws Exception { return super.userDetailsServiceBean(); } } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/resources/**"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/user/getEmployeesListRole/**").access("hasAuthority('WRITE_DATA') && hasAuthority('READ_DATA')").anyRequest().permitAll().and().formLogin().permitAll().and().logout().permitAll().and().csrf().disable(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("admin").password("admin").authorities("WRITE_DATA", "READ_DATA"); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override @Bean public UserDetailsService userDetailsServiceBean() throws Exception { return super.userDetailsServiceBean(); } } 
0
source

You do not need @EnableWebSecurity on Oauth2SecurityConfiguration @EnableResourceServer . You should also replace extends WebSecurityConfigurerAdapter with extends ResourceServerConfigurerAdapter .

If you want to use an instance of RemoteTokenServices , I recommend that you override ResourceServerConfigurerAdapter public void configure(ResourceServerSecurityConfigurer resources) throws Exception with

 @Override public void configure( ResourceServerSecurityConfigurer resources ) throws Exception { resources.tokenServices( serverConfig.getTokenServices() ); } 
-1
source

Source: https://habr.com/ru/post/1234054/


All Articles