DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Configuring SSO Using WSO2 Identity Server
  • 10 Ways To Keep Your Java Application Safe and Secure
  • What D'Hack Is DPoP?
  • Building OAuth 2.0 Authorization Server

Trending

  • Data Quality: A Novel Perspective for 2025
  • Why Database Migrations Take Months and How to Speed Them Up
  • How Can Developers Drive Innovation by Combining IoT and AI?
  • Comprehensive Guide to Property-Based Testing in Go: Principles and Implementation
  1. DZone
  2. Software Design and Architecture
  3. Security
  4. OAuth in headless applications

OAuth in headless applications

By 
Giorgio Sironi user avatar
Giorgio Sironi
·
Oct. 13, 11 · Interview
Likes (1)
Comment
Save
Tweet
Share
24.9K Views

Join the DZone community and get the full member experience.

Join For Free

OAuth is a wonderful standard: it allows users to give permissions to a third-party service to use theirs accounts on a website; but it works without forcing them to share their password like a phishing website would do.

The typical use of OAuth is for accessing the Facebook, Twitter or Google+ Api (social networks have lots of data to share). It works like a charm:

  1. An URL on socialnetwork.com is generated, that the user loads. A callback URL pointing to your application is attached as a GET param.
  2. Since the user is logged in (or he can log in with a simple form) on socialnetwork.com, a token is randomly generated and authorized. In case some permissions are required the user is prompted for approval.
  3. The user is redirected back to your application with the token, that now you can use to make requests. You never get to know the user's password.
A full explanation of OAuth is out of the scope of this post; what I want to tackle today is how to use OAuth inside an headless application such as Jenkins, PHPUnit or Ant.

Headless application?

An headless application does not have a real user interface, and which can run in background for days. Consider for example Jenkins performing builds for Continuous Integration; a Selenium server; or a crawler loading web pages all day on a server machine.

The point is in headless application you cannot send the user (who may be yourself) to a browser for approval at every reboot (for example because the process runs on a CI machine.) And usually, the social network can't redirect the user to the headless application with an HTTP Location header.

However, in the cases we are interested in a user is needed in order to make requests to the Api. Most social networks allows you to make many kinds of Api calls only after having logged in with an user.

Thus we have to split up our application in two parts: one (small) whose job is to obtain the authentication token, and one for using it as normal.

Obtaining the token

The assumption we make (see the relevant section at the end of the article) is that long-lived tokens are available for authorization. LinkedIn works like this, and I used my own user for authorizations to make Api calls for groups data.

I integrated an example of authorization from Scribe, the simplest Java library for OAuth. You load the URL provided by Scribe in a browser, follow the website-specific authorization procedure and then paste back the verifier parameter in Scribe.

However, I printed the token instead of using it immediately, and saved it in a .properties file which is ignored by Git via configuration, in order to avoid publishing it in a source code repository. Beware, a commit remains in the repository forever!

import java.io.IOException;
import java.util.Properties;
import java.util.Scanner;

import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.LinkedInApi;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;

public class LinkedInConfigurator {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
	    try {
		Properties properties = LinkedInDefault.getConfiguration();
		
		OAuthService service = new ServiceBuilder()
	        .provider(LinkedInApi.class)
	        .apiKey(properties.getProperty("apiKey"))
	        .apiSecret(properties.getProperty("apiSecret"))
	        .callback("http://localhost")
	        .build();
			
		Scanner in = new Scanner(System.in);
	
		System.out.println("Fetching the Request Token...");
		Token requestToken = service.getRequestToken();
		System.out.println("Got the Request Token!");
		System.out.println();
	
		System.out.println("Now go and authorize Scribe here:");
		System.out.println(service.getAuthorizationUrl(requestToken));
		System.out.println("And paste the verifier here");
		System.out.print(">>");
		Verifier verifier = new Verifier(in.nextLine());
		System.out.println();
		System.out.println("Trading the Request Token for an Access Token...");
		Token accessToken = service.getAccessToken(requestToken, verifier);
		System.out.println("The access token is [accessToken, accessSecret]: " + accessToken);
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	}

}
The storing process is manual in my case, but you can easily save the token wherever you want.

Using the token

To use the access token, instantiate Scribe OAuthService again, along with the Token: you should pass to the constructor the two informations obtained from dumping it (token value and secret).

Now you can create requests and pass them to the service along with the token to be signed. The headless application acquire all the permissions that the user has in the Api.

import static org.junit.Assert.assertTrue;

import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;

public class ScribeLinkedInService implements LinkedInService {

	private OAuthService oauthService;
	private Token accessToken;

	public ScribeLinkedInService(OAuthService oauthService, Token accessToken) {
	    this.oauthService = oauthService;
	    this.accessToken = accessToken;
	}

	@Override
	public String getLastPostsResponse(int groupId, int numberOfPosts,
			long timestampToStartFrom) {
	    OAuthRequest request = new OAuthRequest(Verb.GET, "http://api.linkedin.com/v1/groups/" + groupId + "/posts?count=" + numberOfPosts + "&modified-since=" + timestampToStartFrom);
	    oauthService.signRequest(accessToken, request);
	    Response response = request.send();
	    return response.getBody();
	}

}

Terms Of Service and expiration

Before jumping to implementation, verify that your social network of choice gives you tokens that you can legally store and do not expire in half an hour.

LinkedIn is where I tested this approach and it explicitly said that if the user specifies so, token are durable and do not expire until explicitly revoked. In fact I'm still using one obtained last week for running my integration tests.

Facebook by default gives you a parameter (in the redirect URL) along with the token that tells you how many seconds the token will last. However, if you ask the user for the offline_access permission in the scope parameter of the OAuth dialog, the token will have an infinite expiry time.

It's not really secure for a user to relinquish the access to his account to the application forever, but I presume you're using your own user (or a dummy one) like I am with LinkedIn. Then, you're already saving your password in the browser, aren't you?

Twitter does not currently expire access tokens, unless your application is suspended or the user rejects it from their settings page. Moreover, it offers a wide public portion of its Api where you do not need an authenticated user to perform requests; these tricks may not be neeeded.

FourSquare does not expire tokens, but may do so in the future.

application authentication security

Opinions expressed by DZone contributors are their own.

Related

  • Configuring SSO Using WSO2 Identity Server
  • 10 Ways To Keep Your Java Application Safe and Secure
  • What D'Hack Is DPoP?
  • Building OAuth 2.0 Authorization Server

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!