Spring Security 6 OAuth2 Authorization Code Flow

217 Views Asked by At

I can't quite figure out how to get my server to exchange the code for an access token with the org.springframework.boot:spring-boot-starter-oauth2-client. I'm using Spring Boot 3.2.2.

In the browser I access my server at http://localhost:8090, then I am redirected to http://localhost:8090/oauth2/authorization/[registrationId], at which point I can see a redirect to the value I provided as the

spring.security.oauth2.client.provider.my_registration.authorization-uri

The expected query params are added to the end of that authorization-uri:

?response_type=code&client_id=my_client_id&state=[the_state_value]=&redirect_uri=http://localhost:8090/redirect

where the redirect_uri is the value I provided as the

spring.security.oauth2.client.registration.my_registration.redirect-uri

The next step is that the provider redirects to my redirect_uri and adds a ?code=... query param, which is supposed to be exchanged for an access token. As far as I can tell I am using the correct value for the

spring.security.oauth2.client.provider.my_registration.token-uri

My assumption was that this exchange would happen automatically too, but instead it seems to get into some sort of redirect loop. In the browser I see

Method     Status    URL
GET        302       http://localhost:8090/redirect?code=[the_code_value]&state=[the_state_value]
GET        302       http://localhost:8090/?continue
GET        302       http://localhost:8090/oauth2/authorization/my_registration
GET        302       https:/[theprovider]/login/oauth2/auth?response_type=code&client_id=my_client_id&state=[the_state_value]&redirect_uri=http://localhost:8090/redirect

Currently I just have withDefaults, so maybe there's something else I need to do in order to get the code exchange to happen.

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests(customizer -> customizer.anyRequest().authenticated());
    http.oauth2Login(Customizer.withDefaults());
    http.oauth2Client(Customizer.withDefaults());
    return http.build();
}

Edit: I have looked at the answer here https://stackoverflow.com/a/62407232/10243546 which suggests removing this to use Spring's default

spring.security.oauth2.client.registration.my_registration.redirect-uri

However if I remove that, the application context won't stand up with this error:

'clientRegistrationRepository' threw exception with message: redirectUri cannot be empty

Edit 2: The token exchange is actually happening. I can see it when debugging the OAuth2AuthorizationCodeAuthenticationProvider. The issue I guess is after that...

enter image description here

0

There are 0 best solutions below