OAuth 2.0 implementation in Spring Framework
Posted By : Kundan Ray Akela | 14-Dec-2014
In this blog , I am going to share OAuth 2.0 implementation in Spring. Unlike from my last blog this will automatically handle response code come to the redirect uri. I also want to show you the flow during OAuth 2.0 implementation.

Image source -google.com
In the above image it is clear the process of Open authentication.First your application make a request to get the token to the server.In the response server authenticate the user by asking userid and password.After successful login of the user , server return the Authorization code on the redirect url. Now using this authorization code in request we get the access token in response.We can now call the api methods of the server using this access token.
Now move through the code for implementing it. I am using Apache Oltu library.
Maven dependency of Oltu library have to write in pom.xml is:
org.apache.oltu.oauth2 org.apache.oltu.oauth2.client 1.0.0
Create controller let name it to OAuthController.java
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class OAuthController
{
public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse response) throws OAuthSystemException, IOException{
OAuthClientRequest request=null;
request = OAuthClientRequest
.authorizationLocation(“your server’s auth location ”)
.setResponseType(“code”)
.setState("1")
.setClientId("your client id")
.setRedirectURI("http://localhost:8080/Scheduler/auth/kounta/callback.html")
.buildQueryMessage();
System.out.println("Url for redirecting::::"+request.getLocationUri());
return new ModelAndView("redirect:"+request.getLocationUri());
}
}
Create callback controller let call it AuthCallbackController.java
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.response.OAuthAccessTokenResponse;
import org.apache.oltu.oauth2.client.response.OAuthAuthzResponse;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class AuthCallbackController
{
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
throws IOException, OAuthSystemException, OAuthProblemException {
OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
String stateResponse = oar.getState();
if (stateResponse.equals("")) {
return new ModelAndView("posIndex","message", "Unsuccessful");
}
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
OAuthAccessTokenResponse oAuthResponse = getAccessToken(oar, oAuthClient);
System.out.println("Hey I am getting access token::::"+oAuthResponse.getAccessToken());
return new ModelAndView("posIndex","message", "successful");
}
private OAuthAccessTokenResponse getAccessToken(OAuthAuthzResponse oar, OAuthClient oAuthClient)
throws OAuthSystemException, OAuthProblemException {
String code = oar.getCode();
OAuthClientRequest request = OAuthClientRequest
.tokenLocation("your server’s token location")
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setClientId("your client id")
.setClientSecret("your client secret")
.setCode(code)
.setRedirectURI("http://localhost:8080/Scheduler/auth/kounta/callback.html")
.buildBodyMessage();
OAuthAccessTokenResponse oAuthResponse = oAuthClient.accessToken(request);
return oAuthResponse;
}
}
Define bean of above classes in your servlet mapping xml file.
oAuthController authCallbackController
Run your application and hit http://localhost:8080/sa/authorize.hhtml and this will ask you for authentication (userid and password) .After successful authentication ,it will redirect you to your rediect url which is http://localhost:8080/auth/kounta/callback.html. The controller mapped for this url is AuthCallbackController. This controller will receive code in response and using this code we will get the access token.
Thanks,
Kundan Ray
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Kundan Ray Akela
Kundan holds years of industry experience as a Fullstack Developer in various technologies and is focused in defining the architecture of the system to ensure reliability and resilience. He possess good knowledge & understanding of latest technologies and hands-on experience in Core Java, Spring-Boot, hibernate, React, Angular , Apache Kafka messaging queue , AI Development like Computer Vision/Generative AI/Prediction System, Internet of Things based technologies and relational database like MySql, PostgreSQL etc. He is proficient in API Implementations, Webservices, Development Testings and deployments, code enhancements and have been contributing to company values through his deliverable in various client projects namely VirginMedia, Konfer, TIHM, Herdsy, HP1T and many more. He has a creative mind and has good analytical skills and likes reading and exploring new technologies.