OAuth 2.0 implementation in Java
Posted By : Kundan Ray Akela | 13-Dec-2014
OAuth is an authentication and authorization system stands for Open Standard for Authorization. It provides the application secure access to server resources.The main thing about the OAuth is that we do not need to share the server credentials.It is specifically desined to work with HTTP.
OAuth provides an access token with the approval of the resource owner.After getting the access token from the resource owner we can call the API methods or more simply we can say that we can access the resources hosted by the resource server.
It is highly recommended for use one of the library that support all the OAuth setup stuff. There are many libraries that provide the OAuth setup.
For java there are the following libraries that supports the OAuth implementation.
- Apache Oltu
- Spring Social
- Spring Security for OAuth
- Restlet Framework (draft 30)
- scribe-java
I am using Apache Oltu library for OAuth 2.0 implementation. The maven dependency of Apache Oltu is:
org.apache.oltu.oauth2 org.apache.oltu.oauth2.client 1.0.0
OAuth implementation consist of two steps for getting token from server.In the first step we receive code in the response .After that we again make a request with code and get access token from the server.
So let’s move to the coding for getting code or temporary token and after using this code or temporary token we will get the access token.
public void OauthMethod(String authLocation,String clientId,String clientSecret,String redirectUri,String tokenLocation)
{
String accessToken="";
OAuthClientRequest outhReq=null;
try {
outhReq = OAuthClientRequest
.authorizationLocation(authLocation)
.setResponseType("code")
.setState("1")
.setClientId(clientId)
.setRedirectURI(redirectUri)
.buildQueryMessage();
} catch (OAuthSystemException e) {
e.printStackTrace();
}
//in web application you make redirection to uri:
log.debug("Visit: " + request.getLocationUri() + "\nand grant permission");
log.debug("Now enter the OAuth code you have received in redirect uri ");
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String tempCode="";
try {
tempCode = br.readLine().trim();
} catch (IOException e) {
e.printStackTrace();
}
try {
outhReq = OAuthClientRequest
.tokenLocation(tokenLocation)
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setClientId(clientId)
.setClientSecret(clientSecret)
.setCode(code)
.setRedirectURI(redirectUri)
.buildBodyMessage();
} catch (OAuthSystemException e) {
e.printStackTrace();
}
OAuthAccessTokenResponse oAuthResponse=null;
try {
oAuthResponse = oAuthClient.accessToken(outhReq);
} catch (OAuthSystemException e) {
e.printStackTrace();
} catch (OAuthProblemException e) {
e.printStackTrace();
}
token=oAuthResponse.getAccessToken();
log.debug("Access Token:"+accessToken);
log.debug("Expires in: "+oAuthResponse.getExpiresIn()+",Refresh token:"+oAuthResponse.getRefreshToken());
}
It will create a url like https://secure.vendhq.com/connect?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&client_id=owhVnBVLtFJGkdDbR3HeGwqbBLv54cl8 and after hitting this url we will get code in the url like http://localhost:8080/auth?code=cd4Frtd9jbddsdffddssg
Please enter the code as an input for the application. The application use the code for making request for getting access token.
This process will be common to all of the websites that are using OAuth 2.0 like facebook, twitter, linkedin, Lightspeed, Kounta and Vend and you have to register the client on their site.
Now we will able to access their API with the access token , some OAuth provider token expires in a particular duration and need to be refreshing using refresh token. This is a sample application for getting access token .I will cover more real approach in the next blog for getting access token in Spring framework.If you have any problem in getting access token through this ,please feel free to comment your queries.
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.