3

I am struggling to do this simple thing in Spring: Redirecting to the Login page when the access token expires.

I have:

  • a Edge Server (Zuul) for routing.
  • a OAuth2 authorization / authentication server.
  • a Resource Server that serves static files.

For specific security reasons I do not want any refresh token, when my TOKEN expires I want the user to login again.

In my understanding the Resource Server should be the one handling this mechanism (correct me if I am wrong).

I have been trying different unsuccessful approaches:

  • Adding a filter After OAuth2AuthenticationProcessingFilter and check for Token validity and sendRedirect
  • Adding a custom OAuth2AuthenticationEntryPoint to my application (extending ResourceServerConfigurerAdapter)
  • Adding .exceptionHandling() with a custom handler / entry point.

Below my security configurations.

Auth Server Security Config:

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerOAuthConfig extends AuthorizationServerConfigurerAdapter {
    ....

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(this.authenticationManager)
                .accessTokenConverter(accessTokenConverter())
                .approvalStore(approvalStore())
                .authorizationCodeServices(authorizationCodeServices())
                .tokenStore(tokenStore());
    }

    /**
      * Configure the /check_token endpoint.
      * This end point will be accessible for the resource servers to verify the token validity
      * @param securityConfigurer
      * @throws Exception
      */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer securityConfigurer) throws Exception {
        securityConfigurer
            .tokenKeyAccess("permitAll()")
            .checkTokenAccess("hasAuthority('ROLE_TRUSTED_CLIENT')");
    }
}

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

    private static final Logger log = LoggerFactory.getLogger(AuthorizationServerSecurityConfig.class);

    @Autowired
    private DataSource oauthDataSource;

    @Autowired
    private AuthenticationFailureHandler eventAuthenticationFailureHandler;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws UserDetailsException {
        try {
            log.debug("Updating AuthenticationManagerBuilder to use userDetailService with a BCryptPasswordEncoder");
            auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
        } catch (Exception e) {
            throw new UserDetailsException(e);
        }
    }

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

    @Override
    public UserDetailsService userDetailsService() {
        return this.userDetailsService;
    }

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        log.debug("Updating HttpSecurity configuration");

        // @formatter:off
        http
            .requestMatchers()
                .antMatchers("/login*", "/login?error=true", "/oauth/authorize", "/oauth/confirm_access")
                .and()
            .authorizeRequests()
                .antMatchers("/login*", "/oauth/authorize", "/oauth/confirm_access").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .failureUrl("/login?error=true")
                .failureHandler(eventAuthenticationFailureHandler);
        // @formatter:on
    }

Its application.yml

server:
    port: 9999
    contextPath: /uaa

eureka:
    client:
        serviceUrl:
            defaultZone: http://localhost:8761/eureka/

security:
    user:
        password: password

spring:
    datasource_oauth:
        driverClassName: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/oauth2_server
        username: abc
        password: 123
    jpa:
        ddl-create: true
    timeleaf:
        cache: false
        prefix: classpath:/templates

logging:
    level:
        org.springframework.security: DEBUG

authentication:
    attempts:
        maximum: 3

Resource Server Security Config - UPDATED:

@EnableResourceServer
@EnableEurekaClient
@SpringBootApplication
public class Application extends ResourceServerConfigurerAdapter {

    private CustomAuthenticator customFilter = new CustomAuthenticator();

    /**
     * Launching Spring Boot
     * @param args
     */
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args); //NOSONAR
    }

    /**
     * Configuring Token converter
     * @return
     */
    @Bean
    public AccessTokenConverter accessTokenConverter() {
        return new DefaultAccessTokenConverter();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.authenticationManager(customFilter);
    }

    /**
     * Configuring HTTP Security
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .authorizeRequests().antMatchers("/**").authenticated()
            .and()
                .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            .and()
                .addFilterBefore(customFilter, AbstractPreAuthenticatedProcessingFilter.class);

        // @formatter:on
    }

    protected static class CustomAuthenticator extends OAuth2AuthenticationManager implements Filter {

        private static Logger logger = LoggerFactory.getLogger(CustomAuthenticator.class);
        private TokenExtractor tokenExtractor = new BearerTokenExtractor();
        private AuthenticationManager authenticationManager;
        private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new OAuth2AuthenticationDetailsSource();
        private boolean inError = false;

        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            try {
                return super.authenticate(authentication);
            }
            catch (Exception e) {
                inError = true;
                return new CustomAuthentication(authentication.getPrincipal(), authentication.getCredentials());
            }
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
                throws ServletException, IOException {

            logger.debug("Token Error redirecting to Login page");

            if(this.inError) {
                logger.debug("In error");

                RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

                final HttpServletRequest req = (HttpServletRequest) request;
                final HttpServletResponse res = (HttpServletResponse) response;

                redirectStrategy.sendRedirect(req, res, "http://localhost:8765/login");

                this.inError = false;
                return;
            } else {
                filterChain.doFilter(request, response);
            }
        }

        @Override
        public void destroy() {
        }

        @Override
        public void init(FilterConfig arg0) throws ServletException {
        }

        @SuppressWarnings("serial")
        protected static class CustomAuthentication extends PreAuthenticatedAuthenticationToken {

            public CustomAuthentication(Object principal, Object credentials) {
                super(principal, credentials);
            }

        }

    }
}

Its application.yml:

server:
    port: 0

eureka:
    client:
        serviceUrl:
            defaultZone: http://localhost:8761/eureka/

security:
    oauth2:
        resource:
            userInfoUri: http://localhost:9999/uaa/user

logging:
    level:
        org.springframework.security: DEBUG

Edge Server Configuration:

@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
@EnableOAuth2Sso
public class EdgeServerApplication extends WebSecurityConfigurerAdapter {

    /**
     * Configuring Spring security
     * @return
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http.logout()
            .and()
                .authorizeRequests().antMatchers("/**").authenticated()
            .and()
                .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
        // @formatter:on
    }

    /**
     * Launching Spring Boot
     * @param args
     */
    public static void main(String[] args) {
        SpringApplication.run(EdgeServerApplication.class, args); //NOSONAR
    }
}

Its application.yml config:

server:
    port: 8765

eureka:
    client:
        serviceUrl:
            defaultZone: http://localhost:8761/eureka/

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

zuul:
    debug:
        request: true
    routes:
        authorization-server:
            path: /uaa/**
            stripPrefix: false
        fast-funds-service:
            path: /**

logging:
    level:
        org.springframework.security: DEBUG

Thanks for the help

LauRiot
  • 31
  • 1
  • 5
  • what do you get with this config?? what's the behavior? any errors? – Ulises Sep 26 '16 at 19:27
  • I am able to login successfully, the OAuth server grant me an Access Token and I am redirected to the Home page. When the token expires I have a 401 invalid_token error. I ultimately would like when the user performs any action with an expired token to be redirected to the login page. – LauRiot Sep 26 '16 at 19:34

2 Answers2

2

Try setting the validity of the refresh token to 0 or 1 seconds.

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.inMemory()
           .withClient("javadeveloperzone")
           .secret("secret")
           .accessTokenValiditySeconds(2000)        // expire time for access token
           .refreshTokenValiditySeconds(-1)         // expire time for refresh token
           .scopes("read", "write")                         // scope related to resource server
           .authorizedGrantTypes("password", "refresh_token");      // grant type

https://javadeveloperzone.com/spring-security/spring-security-oauth2-success-or-failed-event-listener/#22_SecurityOAuth2Configuration

Chloe
  • 25,162
  • 40
  • 190
  • 357
1

Based on your comment you can add this:

http.exceptionHandling()
    .authenticationEntryPoint(unauthorizedEntryPoint())

@Bean
public AuthenticationEntryPoint unauthorizedEntryPoint() {
    return (request, response, authException) -> response.response.sendRedirect("/login"));
}
Ulises
  • 9,115
  • 2
  • 30
  • 27
  • Thanks @Ulises I did try this approach and retried it with your proposed solution but the exceptionHandling() does not seems to be called. – LauRiot Sep 26 '16 at 19:55
  • I can see debugging the Spring code that the event publisher in OAuth2AuthenticationProcessingFilter publishes a BadCredentialsException and call the OAuth2AuthenticationEntryPoint.commence with an InsufficientAuthenticationException. – LauRiot Sep 26 '16 at 19:58
  • Can you post all your config? – Ulises Sep 26 '16 at 20:01
  • I did update the description. I believe all the relevant part are there. Thanks for helping – LauRiot Sep 26 '16 at 20:47
  • You're' using oauth2 authorization server out of the box right? – Ulises Sep 26 '16 at 20:48
  • Yes I do, with Authorization Code. – LauRiot Sep 26 '16 at 20:50
  • Now that I look closely to your example, where did you try what I suggested? In the Resource Server?? – Ulises Sep 26 '16 at 21:11
  • I did try in both the Resource Server and Authorization Server – LauRiot Sep 26 '16 at 21:27
  • So I did move a bit forward, I am now able to redirect to the login page from my resource server. A discussion of a Spring user with Dave Syer helped me: https://github.com/spring-projects/spring-security-oauth/issues/388. Nevertheless it does not solve fully my issue, even if I am redirected to the login page, instead of asking the user to enter its credentials it does authenticate him directly... – LauRiot Sep 27 '16 at 20:00