Spring Boot with the OAuth 2 Password Grant

Posted By :Harshit Verma |26th February 2020

OAuth (Open Authorization) is a simple way to publish and communicate with the ensured information.It is the open standard for token-based authentication and authorization on a Internet. It allows an end user's account information to be used by the third-party services, such as Facebook, without exposing a user's password. When utilizing OAuth2, grant type is the manner in which an application gets the entrance token. Following are the grant types as indicated by OAuth2 determination 

-> Implicit grant
-> Resource owner credentials grant
-> Client credentials grant
-> Refresh token grant


 Oauth usually consists of following actors -

Resource Owner(User) - A entity fit for giving access to a secured asset. At the point when the asset proprietor is an individual, it is alluded to as an end-user.

 

Client Application - Machine that needs to be authenticated.

 

Authorization Server - Server giving access tokens to the customer after effectively validating the asset proprietor and getting the approval.

 

Resource Server - Resource server is OAuth 2.0 term for API server. The resource server handles the authenticated requests after application has obtained the access token.

 

If there should be an occurrence of Password grant type the client triggers the customer to get some asset. At the same time it passes the username and secret word to the customer. The customer at that point speaks with the approval server utilizing the gave username, secret phrase and furthermore its own clientId and clientSecret to get the entrance token. Utilizing this entrance token it at that point gets the necessary asset from the asset server. So two calls are required to be made by the customer application to get the asset,hit to the Auth Server to get the token.

 

 Parameter                             Value

-> grant_type (required)         client_credentials
-> client_id(required)             The client id
-> client_secret(required)      The client secret key
-> username(required)            The username of the user
-> password(required)            The password of the user


In the wake of getting the token from the authorization server, the client application then needs to utilize this for getting asset from the resource server.The genuine case of Password grant will be you doing a login to you facebook account utilizing its versatile application. Here the client should indicate the facebook qualifications to the application. Additionally the application will have its own client id and client secret.


Authorization Server

Create the Authorization Server which will generate the token for client.And the Maven we need to include the  Spring oauth dependency. Maven will be as follows-

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.javainuse</groupId>
	<artifactId>boot-oauth2-password-authorization-server</artifactId>
	<version>0.0.1.SNAPSHOT</version>


	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.3.0.RELEASE</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.security.oauth</groupId>
			<artifactId>spring-security-oauth2</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

Define the Spring Boot Main Application. Here we have defined vaidateUser API which will validate if a token is valid. Also we have configured a basic Auth using in memory authentication for username and password.

package com.javainuse;

import java.security.Principal;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@EnableResourceServer
@SpringBootApplication
public class Application {

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

	@RequestMapping("/validateUser")
	public Principal user(Principal user) {
		return user;
	}

	@Configuration
	protected static class AuthenticationManagerConfiguration extends GlobalAuthenticationConfigurerAdapter {

		@Override
		public void init(AuthenticationManagerBuilder auth) throws Exception {
			auth.inMemoryAuthentication().withUser("javainuse-user").password("javainuse-pass").roles("USER");
		}

	}
}

 

Configure the Authorization Server. The @EnableAuthorizationServer annotation is used to configure OAuth 2.0 Authorization Server mechanism and defines behaviour of various endpoints when interacting with authorization server.
 

package com.javainuse.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {

	@Autowired
	private AuthenticationManager authenticationManager;

	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
		endpoints.authenticationManager(authenticationManager);
	}

	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		clients.inMemory().withClient("javainuse-client").secret("javainuse-secret")
				.authorizedGrantTypes("password").scopes("read", "write");

	}
}

 

Resource Server

Make the Resource Server which has an asset to be gotten to by customer. Maven Project will be as follows- Spring Boot OAuth2 Password Grant Maven
In the Maven we need  to include the Spring oauth dependency. Maven will be as follows-

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.javainuse</groupId>
	<artifactId>boot-oauth2-resource-server</artifactId>
	<version>0.0.1.SNAPSHOT</version>


	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.3.0.RELEASE</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.security.oauth</groupId>
			<artifactId>spring-security-oauth2</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>


Define the Spring Boot Main Application. Configure the Resource Server using @EnableResourceServer annotation. It means a service expects an access token in order to process a request. Access token should be obtained from the Authorization Server by OAuth 2.0 Client before calling the Resource Server.
 

package com.javainuse;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.web.bind.annotation.RestController;

@EnableResourceServer
@SpringBootApplication
public class Application {

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

create the Controller, to expose the  API which can be accessed only using  the valid token.

package com.javainuse.controller;

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

@RestController
public class TestController {

	@RequestMapping("/test")
	public String test() {
		return "Hello World";
	}
}

Next,the url of the authorization server to be called by a resource server for verifying the token in application.yml as follows.

security:
  oauth2:
    resource:
      userInfoUri: http://localhost:8080/validateUser
server:
  port: 9090

Finally initiate the Authorization Server and the Resource Server.
First get a access Token by making the POST request to  the localhost:8080/oauth/token
Specify both the client_id and client_secret in a header using base64 encoding.
Spring Boot OAuth2 Password Grant - Token
Next specify a grant type as the Password Grant in the body and send a request.
Spring Boot OAuth2 Password Grant - Token Example
We get the token as response
catch the Resource by a access token received above and making the GET call to localhost:9090/test.
The token is specified as the Authorization Bearer.

 

 


About Author

Harshit Verma

Harshit is a bright Web Developer with expertise in Java and Spring framework and ORM tools Hibernate.

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us