Click here to Skip to main content
14,972,394 members
Articles / Hosted Services / Azure
Article
Posted 6 May 2021

Tagged as

Stats

1.2K views

Java on Azure: Cloud-Native Authentication

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
6 May 2021CPOL3 min read
In this next part of this series, we look at how your application knows it is in use. We also look at how Azure provides support through its services and free code libraries for authenticating your user.

This article is a sponsored article. Articles such as these are intended to provide you with information on products and services that we consider useful and of value to developers

An API often needs to identify its caller. It could be a web application calling an API, or another API calling an API. Identifying the caller of an API is also known as authentication. Building one’s own authentication framework can be tricky. Thankfully, one does not have to build up their own authentication framework. There are solutions already available. Azure Active Directory (Azure AD), the Microsoft Authentication Library (MSAL), works across a variety of platforms for handling tokens and authentication.

Azure AD provides a way for a user to use pre-existing credentials provided by an organization to sign in to an application instead of making a new sign-in for every application. Using Azure AD frees your application from many of the tasks associated with user maintenance, such as sign-in and password reset. An OAuth flow authenticates a user then temporarily hands the user off to another page for signing in. After signing in, the page passes back an access token to the application. The application can use the access token to retrieve further information about the current user.

Creating a Tenant

To begin using Azure AD, you need to have access to an Azure AD tenant. A tenant represents an organization. You may already have a tenant set up for your account. To check, log into the Azure portal and look in the upper right. If your account is set up for a tenant, it appears under your username.

Image 1

If you don’t already have an Azure AD tenant, you can create one. In the Azure portal, select "Azure Active Directory." From the menu on the top, select "Create a tenant."

Image 2

Select "Azure Active Directory" as the tenant type and click Next. Fill in the information for your organization and continue to create the tenant.

Image 3

Once you have a tenant, you must register your application as a client of Azure AD. In the portal, select "Azure Active Directory." Under the Manage menu, select "App registrations" and then click +New registration.

Image 4

Provide a name for the application that your users will recognize and ensure that you’ve selected your tenant from the "Supported account types" option. Click Register to create your tenant.

Image 5

Adding it to the App

Now that you have set up a tenant, the Microsoft Authentication Library for Java (MSAL4J) will manage authentication. You add MSAL4J to a project by adding a dependency declaration to a project’s Maven repository. Once added, the library’s classes are available through the com.microsoft.azure.msal4j namespace.

XML
<dependency>
    <groupId>com.microsoft.azure</groupId>
    <artifactId>msal4j</artifactId>
    <version>1.9.1</version>
</dependency>

MSAL4J supports different authentication scenarios. Two common scenarios are:

  • A user must authenticate with an application.
  • Services must authenticate with an application.

You can use OAuth for scenarios when a user must authenticate. OAuth is an open standard that enables one website or service to perform authentication for another without sharing the user’s credentials. The application forwards the user to a login page, and the user logs in with their account credentials. Once authenticated, the page sends the user back to the application and gives the application an authentication token for the user. The application uses the authentication token to retrieve an access token. MSAL4J simplifies retrieving the token. In our application, add the following code to retrieve the access token.

JavaScript
//ConfidentialClientApplication app;
String authCode = authorizationCode.getValue();
AuthorizationCodeParameters parameters = AuthorizationCodeParameters.builder(
        authCode,
        new URI(currentUri)).
        build();
IAuthenticationResult result  = app.acquireToken(parameters).get();
SessionManagementHelper.storeTokenCacheInSession(httpServletRequest,
app.tokenCache().serialize());

For web calls that require authentication, add the access token to the header for the call. Azure AD also offers an endpoint that provides information about the user in a JSON object when called with the access token.

JavaScript
HttpURLConnection connection = (HttpURLConnection) MSGraphEndpoint;
 connection.setRequestProperty("Authorization", "Bearer " + accessToken);
 connection.setRequestProperty("Accept", "application/json");
 String response = HttpClientHelper.getResponseStringFromConn(connection);

 int responseCode = conn.getResponseCode();
 if(responseCode != HttpURLConnection.HTTP_OK) {
      throw new IOException(response);
 }
 JSONObject userInformation  = HttpClientHelper.processResponse(responseCode,
 response);

Try running the application yourself. When you run the application, it will now check to see if the user signed in. If the user did not sign in, the user sees a link to the sign-in page. Once the user signs in, the page displays a message that the user has successfully signed in and displays basic information.

Conclusion

Azure provides other functionality that you can use to enrich the functionality of an application. In the next part of this series, we look at Azure Cognitive Services and how we can use existing cloud-native services.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Joel Ivory Johnson
Software Developer
United States United States
I attended Southern Polytechnic State University and earned a Bachelors of Science in Computer Science and later returned to earn a Masters of Science in Software Engineering. I've largely developed solutions that are based on a mix of Microsoft technologies with open source technologies mixed in. I've got an interest in astronomy and you'll see that interest overflow into some of my code project articles from time to time.



Twitter:@j2inet

Instagram: j2inet


Comments and Discussions

 
-- There are no messages in this forum --