Home > Mobile >  Spring Security: Purpose of .oauth2Client(withDefaults()); in HttpSecurity
Spring Security: Purpose of .oauth2Client(withDefaults()); in HttpSecurity

Time:10-31

This is from the doc

public HttpSecurity oauth2Client​(Customizer<OAuth2ClientConfigurer> oauth2ClientCustomizer) throws java.lang.Exception

Configures OAuth 2.0 Client support.

Example Configuration

The following example demonstrates how to enable OAuth 2.0 Client support for all endpoints.

 @Configuration
 @EnableWebSecurity
 public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
                http
                        .authorizeRequests((authorizeRequests) ->
                                authorizeRequests
                                        .anyRequest().authenticated()
                        )
                        .oauth2Client(withDefaults());
        }
 }
 

Parameters: auth2ClientCustomizer - the Customizer to provide more options for the OAuth2ClientConfigurer

Returns: the HttpSecurity for further customizations

The thing I understood is any requests coming to this server should be authenticated.

How does .oauth2Client(withDefaults()); help in this case?

If I'm not wrong, an oAuth2 client is the one sending the requet, what can we actually configure about this? The documentation doesnt really explain much.

CodePudding user response:

The http instance of HttpSecurity is a "bean settings server/application side".

Its method oauth2Client is not related to client configurations, but how and where the server/application should handle them.

Example:

  • Which clients have been authorized
  • Where to store authorized clients
  • How to authorize clients
  • How to remove an old authorized client

CodePudding user response:

I think here , you can find more details about oauth2Client defaults .

@EnableWebSecurity
public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .oauth2Client(oauth2Client ->
                oauth2Client
                    .clientRegistrationRepository(this.clientRegistrationRepository())
                    .authorizedClientRepository(this.authorizedClientRepository())
                    .authorizedClientService(this.authorizedClientService())
                    .authorizationCodeGrant(authorizationCodeGrant ->
                        authorizationCodeGrant
                            .authorizationRequestRepository(this.authorizationRequestRepository())
                            .authorizationRequestResolver(this.authorizationRequestResolver())
                            .accessTokenResponseClient(this.accessTokenResponseClient())
                    )
            );
    }
}
  • Related