Spring Security OAuth2 User Registration

In my last article, we developed a spring security 5 OAuth application with google sign in and customized most of the default behavior. In this article, we will take a deeper look into customizing OAuth2 login. We have already added social login support to our app and now we will extend it to have an option for custom user registration or signup using email and password. After successful registration, we should be able to support JWT token-based authentication in the app.

Primarily, we will be adding below support in our app.

  • Add custom login page in oauth2Login() element.

  • User can choose login options with either custom email and password or social login with Google OAuth.

  • After a successful login, JWT token should be generated and token-based authentication is enabled and user is redirected to /home.

Spring Security OAuth Configuration

To get started with the app, first of all let us review the OAuth configuration that we did in our last article. Below was the final security config where we have customized the oauth2Login() element to have custom redirection point, user info endpoint, user service, authorization endpoint etc. You can visit this article for details. SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private OidcUserService oidcUserService;

    @Autowired
    private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated()
                .and()
            .oauth2Login()
                .redirectionEndpoint()
                .baseUri("/oauth2/callback/*")
            .and()
                .userInfoEndpoint()
                .oidcUserService(oidcUserService)
            .and()
                .authorizationEndpoint()
                .baseUri("/oauth2/authorize")
                .authorizationRequestRepository(customAuthorizationRequestRepository())
            .and()
                .successHandler(customAuthenticationSuccessHandler);

    }

    @Bean
    public AuthorizationRequestRepository customAuthorizationRequestRepository() {
        return new HttpSessionOAuth2AuthorizationRequestRepository();
    }


}

Customizing Login Endpoint

By default, the OAuth 2.0 Login Page is auto-generated by the DefaultLoginPageGeneratingFilter and it is available at /login. To override the default login page, configure oauth2Login().loginPage() with your custom url. Here, we hav configured it as /auth/custom-login. So, our configure() method becomes

Creating Custom Login Page

With the above configuration, whenever any authentication is required, user will be redirected to /auth/custom-login. Now let us create a login page as login.html. In the above security config, we have configured authorizationEndpoint as /oauth2/authorize and hence on the click of Google icon, user will be redirected to /oauth2/authorize/google login.html

Spring Security Config for Registration

To configure our registration process we will be using exisitng implementation - Spring Boot Jwt. Below is our final security config to accomodate the custom login.

Here, we have injected UserDetailsService required by auth manager to fetch the users from the DB. We have configured our Bcrypt password encoder and added custom filter to intercept before UsernamePasswordAuthenticationFilter and validate the token and set the security context.

We have allowed all the request for matcher /auth and configured login page to be available at "/auth/custom-login". We have registred our custom authentication entry point that will redirect any unauthenticated user to login page. SecurityConfig .java

With above configuration, we have achieved below points

1. If an user tries to access any secured page without login e.g. localhost:8080, then he will be redirected to localhost:8080/auth/custom-login.

2. On login page, we have 2 different options to login. Either user can signup with email address and password or else can choose to sign with Google.

3. In both the cases, after a successfull authentication the user will be redirected to /home. JwtAuthenticationEntryPoint.java

JWT Authentication Filter Implementation

Below is the filter implementation that intercepts all the request and checks if the token is present in the URL. If the token is present then it will validate the token and set the security context will be set and the request will be chained to next filter in the filter chain. This is the filter which will be executed before UsernamePasswordAuthenticationFilter. JwtAuthenticationFilter.java

Spring Controller for Custom Login

Below REST endpoints are responsible for generating our custom login page and accepts sign up request. AuthController.java

UserController.java

This endpoint will be executed post login and loads the home page.

Service Implementation For Custom User Authentication

Below implementation will be used by spring security to authenticate user. UserDetailServiceImpl.java

Below implementation is for creating entries of new user in the DB. UserServiceImpl.java

Below is the util class that we are using for generating and validating our JWT token. JwtTokenUtil.java

Running the Final Application

Import the project as a Maven project and make sure your DB configuration matches with those defined in application.properties.

Run SpringBootGoogleOauthApplication.java as a java application.

Now open your browser and hit localhost:8080/auth/custom-login to see the login page.

Conclusion

In this tutorial, we looked into providing support for custom user registration in an existing spring boot OAuth2 application. We used spring security 5 and JWT for our custom token generation process.

Last updated

Was this helpful?