Search code examples
javaspringspring-bootoauth-2.0oauth

Spring Boot redirection back to login page


I am using Spring Boot and authorization server,

This is my application.yml security section:

  security:
    oauth2:
      client:
        provider:
          auth0:
            authorization-uri: http://localhost:5556/auth0/auth
            token-uri: http://localhost:5556/auth0/token
            jwk-set-uri: http://localhost:5556/auth0/keys
        registration:
          auth0:
            client-id: sample-app
            client-secret: ZXhhbXBsZS1hcHAtc2VjcmV0
            client-name: Sample App
            scope: openid
            authorization-grant-type: authorization_code
            redirect-uri: http://localhost:8085/callback

and this is my filter chain:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        
            http
                .authorizeRequests()
                .antMatchers("/callback").permitAll()
                .anyRequest().authenticated()
                .and()
                .oauth2Login();
        
    }
}

When I open my browser, type in one of my Spring Boot GET endpoints, I see login page asking for username/password. I type them in, press "Login" and see button "Grant access". I press it and see endpoint response. But subsequent requests to endpoints do not contain any bearer token. Shouldn't there be a token in the headers, once I authorize?


Solution

  • What is missing is the oAuthCheck in SecurityConfig

    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
    
    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .antMatchers("/login/oauth2/code/dex").permitAll()
                    .anyRequest().authenticated()
                    .and()
                .oauth2Login()
                    .and()
                .oauth2ResourceServer()
                    .jwt()
                    .jwtAuthenticationConverter(jwtAuthenticationConverter());
        }
    
        private JwtAuthenticationConverter jwtAuthenticationConverter() {
            JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
            // Customize the converter if needed
            return converter;
        }
    }