How to prompt for username and password when acquiring an access token in Java

1.1k views Asked by At

When the following C# code is executed, the user is prompted (by an ADAL window) to enter a username and password.

AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/common", false);
AuthenticationResult result = authContext.AcquireToken(serviceUrl, clientId, new Uri(redirectUrl));

I am converting the code to Java using ADAL for Java from GitHub. I do not see any acquireToken() method call that matches the one I used in C#. The code I am currently using is:

AuthenticationContext context = new AuthenticationContext(
    "https://login.windows.net/common", false, service);
Future<AuthenticationResult> future = context.acquireToken(RESOURCE_URL, CLIENT_ID, username, password, null);
AuthenticationResult result = future.get();

However, ADAL does not prompt for username/password. I have to add Java code to my console app to do that. Is there a better way? I would prefer to have the same experience as in the C# version.

Thanks

2

There are 2 answers

0
Yi Li On

Currently, there isn't support to pop up a ADAL window through Java.

0
Navya Canumalla On

ADAL Java does not support a method to prompt user interaction today as the user interaction varies in Java applications based on the platform.

But it is possible to use ADAL Java Auth code flow to acquire tokens in the context of a user in a web application. You will need to craft a request to first acquire the Authorization code from the /authorize endpoint of Azure AD. This allows the user to authenticate with their username and password on the Azure AD login page. You can then call the method acquireTokenByAuthorizationCode to get tokens for the user. Here is a sample for this flow.

If you need user to authenticate at the Azure AD login prompt in a console application, you can also consider the device code flow.