0

I have a spring zuul OAuth2 app.

authServer--

OAuth2ServerConfiguration:

@Configuration
public class  {
    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends
            ResourceServerConfigurerAdapter {

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {
            resources.resourceId(RESOURCE_ID);
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {            http .authorizeRequests()
                    .antMatchers( "/oauth/authorize/**","/oauth/check_token/**").permitAll()

                    .anyRequest().authenticated();
            // @formatter:on
        }

    }

    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends
            AuthorizationServerConfigurerAdapter {

        //private TokenStore tokenStore = new InMemoryTokenStore();
        @Autowired
        @Qualifier("authenticationManagerBean")
        private AuthenticationManager authenticationManager;


        @Autowired
        TokenStore tokenStore;

        @Autowired
        private CustomUserDetailService customUserDetailService;



        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints)
                throws Exception {
            // @formatter:off
            endpoints
                    .tokenStore(this.tokenStore)
                    .authenticationManager(this.authenticationManager)
                    .userDetailsService(customUserDetailService);
            // @formatter:on
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            // @formatter:off
            clients
                    .inMemory()
                    .withClient("kksdi2388wmkwe")
                    .authorizedGrantTypes("authorization_code","password", "refresh_token")
                    .scopes("read", "write")
                    .resourceIds("ReadAndWriteResource")
                    .secret("kksd23isdmsisdi2")
                    .autoApprove(true)
                    .accessTokenValiditySeconds(120)
                    .refreshTokenValiditySeconds(1200);
            // @formatter:on
        }

        @Bean
        @Primary
        public DefaultTokenServices tokenServices() {
            DefaultTokenServices tokenServices = new DefaultTokenServices();
            tokenServices.setSupportRefreshToken(true);
            tokenServices.setTokenStore(this.tokenStore);
            return tokenServices;
        }

    }
}

webSecurity:

@Configuration
@EnableWebSecurity
@Order(-20)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

     @Autowired
    private CustomAuthenticationProvider customAuthenticationProvider;



    @Override
     protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(customAuthenticationProvider);

    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }



    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
                .authorizeRequests()
                .antMatchers("/login", "/").permitAll()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()

                .and()
                .csrf().disable()
                .requestMatchers().antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access")
                .and()
                .authorizeRequests().anyRequest().authenticated()
        ;

        // @formatter:on
    }


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(11);
    }


}

zuul server:

security:
  user:
    password: none
  oauth2:
    client:
      accessTokenUri: http://localhost:9999/uaa/oauth/token
      userAuthorizationUri: http://localhost:9999/uaa/oauth/authorize
      clientId: kksdi2388wmkwe
      clientSecret: kksd23isdmsisdi2
        resource:
      userInfoUri: http://localhost:9999/uaa/user


zuul:
  routes:
    auth-server: /auth-server/**
    resource: /resource/**

zuul app:

@SpringBootApplication
@EnableZuulProxy
@EnableOAuth2Sso
public class Application extends WebSecurityConfigurerAdapter {

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

  @Override
  public void configure(HttpSecurity http) throws Exception {


    http
            .logout().permitAll()
            .and().authorizeRequests()
            .mvcMatchers("/login/**").permitAll()
                      .anyRequest().authenticated();
  }


}

problem:

after logged in:

can access: AuthServer "http://localhost:8080/auth-server/uaa/user" and "http://localhost:8080/api/test"


but when access_token expired, can oly access: "http://localhost:8080/api/test", when accessing AuthServer "http://localhost:8080/auth-server/uaa/user" met error--

<error_description>
Access token expired: 530c9247-2331-47e3-a6c0-ed61814642f5
</error_description>
<error>invalid_token</error>

and I can't get access_token from request header,

How to resolve?

Kery Hu
  • 5,626
  • 11
  • 34
  • 51

2 Answers2

0

Before everything check your OAUTH server application server and your client application server time and timezone if they are separated in two different machine.

Your OAUTH Server Configuration I think has some problems. OAUTH Server itself is secured with 'BASIC ACCESS AUTHENTICATION' : https://en.wikipedia.org/wiki/Basic_access_authentication

Which works with a token on his requests headers : 'Authorization' : Basic=Base64.encode(username+' '+password). If you miss this token then you can't access any endpoint on your OAUTH server. Mine works fine, you can test it:

@Override
protected void configure(HttpSecurity http) throws Exception {
    // @formatter:off
    http.formLogin().loginPage("/login").permitAll()
            .and().requestMatchers().antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access", "/fonts/**", "/css/**")
            .and().authorizeRequests().antMatchers("/fonts/**", "/css/**").anonymous().anyRequest().authenticated();
    // @formatter:on
}

And why have you disabled csrf protection?

Pasha
  • 1,534
  • 15
  • 27
  • Hi,thanks your answer, In order to simplify the problems ,csrf was disabled.I can login in,and access: `AuthServer "http://localhost:8080/auth-server/uaa/user"` by zuul proxy and` "http://localhost:8080/api/test"`,but after 120s,access_token expired, can only ` "http://localhost:8080/api/test"` be accessed, but `AuthServer "http://localhost:8080/auth-server/uaa/user"` can not be accessed . and the error is : `Access token expired: a09e4446-a01c-4e8a-86c4-635c1a30c4fb invalid_token` – Kery Hu Nov 27 '16 at 05:56
  • I have this problem too! the access_token dosen't get renewed and I have to resend authorization_code again to get a new access_token. – Pasha Nov 27 '16 at 07:34
  • Sorry to hear it... I have struggled this problem two days ... I used to use JWT without this problem, but instead of customTokenStore or InMemoryTokenStore there is a problem. – Kery Hu Nov 27 '16 at 07:38
  • I think its not related to your token store, I changed it too, let me send you my own token store maybe find a clue : – Pasha Nov 27 '16 at 07:48
  • In theory, spring zuul, should be able to refresh the access_token, but do not know why not, and if not by zuul, when the token expired, and access to the secured URL `localhost:8080/api/test`, seems contradictory, do not know where the problem – Kery Hu Nov 27 '16 at 07:50
0

these are my token store configuration :

@Autowired
    @Qualifier("datasource")
    private DataSource dataSource;

    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }


    @Bean
    protected AuthorizationCodeServices authorizationCodeServices() {
        return new JdbcAuthorizationCodeServices(dataSource);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer)
            throws Exception {
        oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)
            throws Exception {
        endpoints.authorizationCodeServices(authorizationCodeServices())
                .authenticationManager(authenticationManager).tokenStore(tokenStore())
                .approvalStoreDisabled();
    }
Pasha
  • 1,534
  • 15
  • 27
  • jdbcTokenStore works? when access_ token expired. whether it can access AuthServer or ResourceServer data? – Kery Hu Nov 27 '16 at 07:53
  • yes it works, you must add some configuration to your resource. – Pasha Nov 27 '16 at 08:01
  • I'm not familiar with jdbc, I try mongodb token store , but not set `authorizationCodeService` and `approvalStoreDisabled()`,,can you try cancel set `authorizationCodeService` to see whether it work? – Kery Hu Nov 27 '16 at 08:54
  • have you added `@SessionAttributes("authorizationRequest") ` and set AuthServer's session value? – Kery Hu Nov 27 '16 at 08:57
  • as Oauth2 Rules, when you use Authorization_Code grant type, you need to save it in your token store. this configuration says dear token store please make a table which I can save my authorization code. so you will have 3 tables in your database, OAUTH_ACCESS_TOKEN , OAUTH_REFRESH_TOKEN and OAUTH_CODE – Pasha Nov 27 '16 at 09:40
  • and if you set .approval(true) then you need another table for saving approvals. in your configuration you have not set approvals – Pasha Nov 27 '16 at 09:41
  • if you need authorization request you can use this attribute. in the Oauth2 Spring Security sample it has used it to showing Client information to user in approval page. So you don't need it. – Pasha Nov 27 '16 at 09:44
  • have you seen this sample app? https://github.com/spring-guides/tut-spring-security-and-angular-js/tree/master/oauth2 – Pasha Nov 27 '16 at 09:45
  • yes,I know this url, It looks like to I need no try custom `authorizationCodeService` and `tokenStore`,,try look for mongo relevant examples, tanks very much! – Kery Hu Nov 27 '16 at 10:22
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/129138/discussion-between-kery-hu-and-pasha-gharibi). – Kery Hu Nov 27 '16 at 10:45
  • I have config jdbc `OAUTH_ACCESS_TOKEN , OAUTH_REFRESH_TOKEN and OAUTH_CODE `,but still not work , whether have another configuration? – Kery Hu Nov 28 '16 at 13:07