Search code examples
javaspring-bootspring-securityoauth-2.0spring-boot-starter-oauth2-client

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


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.


Solution

  • 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