Search code examples
javaoauthoauth-2.0

How to authenticate with login and password using OAuth2?


I'm writing a service with no UI that must connect to a web API using OAuth2. I have everything - Client ID, Client Secret, Auth URL, Callback URL, Username, and Password.

I want to know the easiest way to exchange the username, password, etc. for an OAuth2 token so I may authenticate with the web API.

I've been looking at Apache Oltu, and the canonical workflow seems to be:

  1. Use OAuthClientRequest to build the request URI
  2. Redirect to the URI so the user can grant access
  3. Retrieve the corresponding code via OAuthAccessTokenResponse and use it to authenticate

Again - I cannot have the app prompt the user; everything must happen programmatically.

I think I'm looking for something like DotNetOpenAuth's ExchangeUserCredentialForToken() method, but for Java.

I'm leaning towards using Apache Oltu, but I'm open to any framework / solution. Thanks!


Solution

  • That depends on the authentication methods implemented by the Authorization Server (the entity that will give you access_tokens).

    At the protocol level, you are looking for the Resource Owner Password Credentials Grant: https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-31#section-4.3

    Not all Authorization Servers implement this though so you will need to check their docs. (e.g Facebook, Twitter, Google don't provide this, as an example).

    It's a really simple interaction, so generally, you won't need a (client) framework for this. Here's a sample of what the HTTP request looks like: https://auth0.com/docs/flows/resource-owner-password-flow