Spring Security OAuth 2 Social Login

In this tutorial, you will learn how to add a Social Login(OAuth 2) feature into your Spring MVC Web application. This will allow users to login to your application with their social network accounts like Facebook, Google, or other large services that support OAuth 2 like for example GitHub.

For video lessons on how to secure your Spring Boot application with OAuth 2.0. and Spring Security 5, please checkout my complete video course OAuth 2.0. in Spring Boot applications.

Spring Security 5 offers very good support for implementing a social login feature and in this tutorial, I am going to use Spring Security 5.

1. Add Spring Security OAuth 2 Client Support

The first step is to add Spring Security 5 OAuth 2 client support to a pom.xml file of my Spring MVC web application.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

This dependency is enough to print the necessary Spring Security and OAuth 2 support into my web application.

Other Dependencies

Because I am building a web application and because I am going to use the Thymeleaf templates to display server-side data in HTML code, I will need to have the following two dependencies in my pom.xml file as well.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Now when the necessary dependencies are added, I am ready to configure the application.properties file of my Spring Boot application to make it support the OAuth 2 login.

2. OAuth 2 Client Configuration

The OAuth 2 support for authentication providers like Facebook, Google, and GitHub is built-in in the Spring Security 5 network. Below are the examples of OAuth 2 client configuration for each.

Facebook

spring.security.oauth2.client.registration.facebook.client-id = <Facebook app id>
spring.security.oauth2.client.registration.facebook.client-secret = <Facebook app secret>

To get Facebook App Id and App secret credentials, you will need to create a new application with Facebook at https://developers.facebook.com/apps/.

Google

spring.security.oauth2.client.registration.facebook.client-id = google-client-id-here
spring.security.oauth2.client.registration.facebook.client-secret = google-client-secret-here

To get Google client id and client secret values you will need to create a new project with Google using Google Console.

GitHub

spring.security.oauth2.client.registration.github.client-id = github-client-id-here
spring.security.oauth2.client.registration.github.client-secret = github-client-secret-here

To get GitHub client id and client secret values, you will need to create a new OAuth app at GitHub.

You can also configure a custom provider for which Spring Framework does not have a predefined configuration. Below is an example of configuration properties for the Okta authorization server.

Okta

server.port=8080
spring.security.oauth2.client.registration.okta.client-id = okta-client-id-here
spring.security.oauth2.client.registration.okta.client-secret = okta-client-secret-here
spring.security.oauth2.client.registration.okta.scope = openid

spring.security.oauth2.client.provider.okta.issuer-uri = {your-okta-app-domain}/oauth2/default

To get Okta client id and client secret values, you will need to create a new developer account with Okta.

Once you have provided configuration for one of the above-mentioned social login providers, you are ready to proceed to the next.

3. Configure HTTP Security

The next step is to use the @EnableWebSecurity annotation and configure the HTTPSecurity object.

Create a new Java class in your project and make it extend the WebSecurityConfigurerAdapter. Annotate this class with a @EnableWebSecurity annotation.

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;

@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {

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

With the above code, our application will redirect user to a social login provider for authentication. Once user successfully authenticates with the social login provider, they will be redirected back to our application to the protected page they have initially requested. Notice that we have also enabled the logout functionality and have configured the logout successful URL.

Let’s create a protected page.

3. Creating a Protected page

In the following code example, I will create a Controller class with a single resource called “users”.

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class UsersController {

    @GetMapping("/users")
    public String getUser(Model model, @AuthenticationPrincipal OAuth2User principal) {

        if (principal != null) {
            model.addAttribute("name", principal.getAttribute("name"));
        }

        return "user";
    }

}

When the /users resource is requested, our application will redirect user to a social login provider to authenticate. If authentication is successful, the user will be redirected back to a /users resource. Because authentication was successful, we can get information about the currently authenticated user using the @AuthenticationPrincipal  annotation which will help us access the OAuth2User object. The OAuth2User is a principal object and from this principal object, we can some user details.

To display the value of a “name” attribute, I will create an HTML Thymeleaf template page.

The user.html file

Notice that the file name is user.html. This is because the getUser() method in the above controller class returns “user” as a view name.

<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
 
        <p th:text="${name}" />
 
 
    </body>
</html>

I hope this short tutorial was of some value to you. Have a look at other OAuth2 related tutorials on this blog. Hopefully, you will find more tutorials that will be of good value to you.

For video lessons on how to secure your Spring Boot application with OAuth 2.0. and Spring Security 5, please checkout my complete video course OAuth 2.0. in Spring Boot applications.

Happy learning! 🙋🏻‍♂️

 

Leave a Reply

Your email address will not be published. Required fields are marked *