Spring Boot Security Example – Single Sign On using OAuth 2

Introduction

Here we will see Spring Boot Security Example – Single Sign On using OAuth 2. Single Sign On or simply SSO is a property of access control of multiple related, yet independent, software systems, where a user logs in with a single set of credentials (username and password) to gain access. Here we will use Spring Boot 2.14.

We will let client access our App by granting access through Github OAuth 2 API. You can also use other OAuth 2 API, such as, Google, Facebook etc. Even you can create your own OAuth 2 server.

For this we need to first register the App into Github. It is assumed that you have a Github account.

You may also like to read Spring Security Examples.

What is OAuth 2?

OAuth is a protocol with which a 3-party app can access your data stored in another website without your account and password. For more information on OAuth 2 then you can read https://oauth.net/2/.

Prerequisites

Knowledge on Java, Spring Boot, Spring Security

Github Account, Spring Boot Security, JSP

Java 8, Spring Boot 2.1.4, Gradle 4.10.2

Example with Source Code

We will now move on to Spring Boot Security Example – Single Sign On using OAuth 2.

First we need to configure OAuth 2 in Github, once it is done then we will create Spring Boot Security Example in Eclipse.

Configure OAuth2 App in Github

Login to your Github profile section .

Then click on Settings from dropdown menu by clicking on your profile picture on top right corner. Next click on Developer settings. The below figure shows the highlighted menu:

spring boot security example - single sign on using oauth 2

Now click on New OAuth App as shown in the below figure to register a new application to use OAuth:

spring boot security example single sign on using oauth 2

Now below screen appears where you have to put the values for the input fields as per your requirements:

spring boot security example single sign on using oauth 2

As you see in the above figure I have entered values for the input fields and as I want to show you how it works, so I have just created this app to test our example.

The most of the fields are self-explanatory. The Authorization callback URL is the URL, where you want to redirect your users after authorization was successful.

Once you click on Register application, your application will be created and you will be redirected to a page, where Client ID and Client Secret get generated. The below figure shows similar page:

spring boot security example single sign on using oauth 2

The Client ID and Client Secret are required to authenticate your app.

Creating Project

Create a gradle based project in Eclipse. The following figure shows the final project structure for Spring Boot Security Example – Single Sign On using OAuth 2.

spring boot security example

Adding Dependencies

Once the gradle project gets created in Eclipse, open build.gradle script in editor and update as follows:

buildscript {
	ext {
		springBootVersion = '2.1.4.RELEASE'
	}
    repositories {
    	mavenLocal()
    	mavenCentral()
    }
    dependencies {
    	classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'org.springframework.boot'
    
sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
	mavenLocal()
    mavenCentral()
}

dependencies {
	compile("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
	compile("org.springframework.boot:spring-boot-starter-security:${springBootVersion}")
	compile("org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.1.4.RELEASE")
	compile('org.apache.tomcat.embed:tomcat-embed-jasper:8.5.14')
    compile('javax.servlet:jstl:1.2')
}

In the above build script we have added Spring Boot Security, OAuth2 for using OAuth 2 API in Spring Boot Security.

We have added tomcat-embed-jasper and servlet APIs for JSP support. In this example we will use JSP as the view technology.

Building the Project

In this state, you can build your project to download all the required jar files from the repository.

If you find exception related to main class not found, then simply add a class with main method under package com.jeejava.sso.oauth2.main or any other package as per your choice to make the build successful. We will modify this main class later.

Config – application.yml

Add application.yml file under classpath directory src/main/resources and modify with below configurations:

#server port
server:
   port: 9000

#OAuth2
security:
   oauth2:
      client:
         clientId: <app's client id>
         clientSecret: <app's client secret>
         accessTokenUri: https://github.com/login/oauth/access_token
         userAuthorizationUri: https://github.com/login/oauth/authorize
         clientAuthenticationScheme: form
      resource:
         userInfoUri: https://api.github.com/user
         preferTokenInfo: false
      
#view resolver
spring:
   mvc:
      view:
         prefix: /view/
         suffix: .jsp

In the above configuration file, we have let Tomcat server know on which it has to start.

Then we configure OAuth 2 using Github’s Client ID, Client Secret and various other URLs.

We want to use JSP as a view technology, so we have also configured for it. You can use any view technology, such as, HTML.

Creating Config Class

We need to create Java config class to configure Spring Security for our OAuth 2. We don’t want to use Spring basic security to authenticate our users. We want to use only OAuth 2 API to authenticate our application.

We have enabled OAuth 2 using @EnableOAuth2Sso annotation on our config class:

package com.jeejava.sso.oauth2.config;

import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableOAuth2Sso
public class SsoConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers("/", "/user", "/login**", "/error**").permitAll().anyRequest()
				.authenticated().and().logout().logoutSuccessUrl("/").permitAll();
		http.csrf().disable();
	}

}

In the above config class we have defined URL patterns, such as, “/”, “/user”, “/login”, “/error” to avoid authentication.

We have called built-in logout functionality to logout the users.

We have also disabled csrf tokens. If you want to use csrf tokens then you don’t need to disable it because by default it is enabled.

Creating REST Controller

We will create Spring REST Controller to retrieve authenticated user’s information:

package com.jeejava.sso.oauth2.controller;

import java.security.Principal;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

	@GetMapping("/user")
	public Principal user(Principal principal) {
		return principal;
	}

}

Because the “home” controller needs an endpoint at “/user” that describes the currently authenticated user as shown in next section.

Creating Controller

We will create Spring Controller to show the home page in the browser.

package com.jeejava.sso.oauth2.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

	@GetMapping("/")
	public String home() {
		return "index";
	}

}

The above controller method when URI matches to “/”, it calls the index page and displays its content on the browser.

Creating View

Create below view called index.jsp and put it under src/main/webapp/view directory.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<title>Spring Boot OAuth2 SSO Example</title>
<head>
	<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
	<script type="text/javascript">
	    $.get("/user", function(data) {
	        $("#user").html(data.userAuthentication.details.name);
	        $(".unauthenticated").hide()
	        $(".authenticated").show()
	    });
	    
	    function logout() {
	        $.post("/logout", function() {
	            $("#user").html('');
	            $(".unauthenticated").show();
	            $(".authenticated").hide();
	        })
	        return true;
	    }
	</script>
</head>
<body>
	<div class="container unauthenticated">
		Login With Github <a href="/login">click here</a>
	</div>
	<div class="container authenticated" style="display: none">
		Logged in as: <span id="user"></span>
		<div>
			<button onClick="logout()" class="btn btn-primary">Logout</button>
		</div>
	</div>
</body>
</html>

The above code is self-explanatory. We are showing the Login link or Logout button depending upon whether a user has been authenticated or not.

We have included jQuery library to work with the jQuery API. We are using jQuery’s get method – $.get() – to get the authenticated user’s information and we show the Logout button with user’s name.

We have added logout() function with onClick event on Logout button and call the standard “/logout” URI from Spring Security’s built-in API.

Creating Main Class

Now we need to create or update if you have already created main class at Building the Project step.

package com.jeejava.sso.oauth2.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = "com.jeejava.sso.oauth2")
public class SsoOAuth2Application {

	public static void main(String[] args) {
		SpringApplication.run(SsoOAuth2Application.class, args);
	}

}

We have added the scanBasePackages to include all annotated classes into the Spring container.

Console Output

Run the above main class and when server is up then you will following output in the console:

[           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 9000 (http) with context path ''
[           main] c.j.s.oauth2.main.SsoOAuth2Application   : Started SsoOAuth2Application in 7.696 seconds (JVM running for 8.568)

Testing the Application

When you hit the URL http://localhost:9000 then user will see below page:

single sign on using oauth2

So user is not able to see the home page of the URL and user needs to authenticate using Github account.

Now when user clicks on click here link, then user will be redirected to the Github login page:

spring boot security example

Once user enters username/password, then user will see below page:

single sign on using oauth 2

Now app will ask user (for example, here roytuts) to authorize in order to access your application. Therefore user needs to click on Authorize roytuts (user) and the user will be redirected to the below page:

spring boot security example

So now user will be able to see the Logout button as the user has been authorized.

Hope you got idea on Spring Boot Security Example – Single Sing On using OAuth 2.

Source Code

You can download the source code.

Thanks for reading.

Spring Boot Security Example – Single Sign On using OAuth 2

Leave a Reply

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

Scroll to top