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.
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."
Select "Azure Active Directory" as the tenant type and click Next. Fill in the information for your organization and continue to create the tenant.
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.
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.
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.
<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.
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.
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.