Click here to Skip to main content
15,887,821 members
Articles / Hosted Services / Azure
Article

Connecting Azure Authentication to Other Providers Article 2: Using Azure AD B2C to Enable Social Login

Rate me:
Please Sign up or sign in to vote.
4.83/5 (3 votes)
10 Jan 2022CPOL7 min read 7.7K   31   5   1
In this article we will learn how to use Azure AD for social login.
Here we will demonstrate how to add Azure AD B2C authentication to a Spring Boot web app (deployed via Azure Spring Cloud) and enable social login with a Microsoft or GitHub account.

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

So many companies offer consumer-facing applications that it becomes a hassle for users to create a brand-new login for each one. You can make it easier for your own customers by letting them log in with their social accounts such as Google, Facebook, Microsoft, and GitHub. Microsoft handles the more painful aspects of authorization and authentication while you focus on finding even more ways to enhance your application’s user experience.

This article demonstrates establishing Azure Active Directory (AD) authentication for social accounts in a Spring Boot application. To follow along with this tutorial, you must have:

  • Some Java experience
  • Access to Azure Cloud Platform
  • Accounts on Outlook.com or Skype
  • The guestBook application from the first article in this series, which provides a basic form for its users to input their feedback

We built the application using the Spring Boot, Spring MVC, and Thymeleaf frameworks. The application is a part of the on-premises AD authentication process. We’ll now configure the same application to integrate the Microsoft platform login process.

Adding Azure Authentication

Azure AD provides rich support for integrating third-party social platforms like Google, Facebook, GitHub, and, of course, Microsoft. The process offers quick and easy user registrations without the pain of a tedious sign-up process. So, the business flow provides convenience to customers while adding user authenticity to the onboarding process.

Setting up a B2C Active Directory

We need a business-to-consumer (B2C) Azure Active Directory (AD) to integrate our application with social platforms. Unlike the vanilla Azure AD, the B2C version is not free and requires a subscription.

As a first step, ensure that your Azure account is associated with an available subscription. Open the Subscriptions view to validate the model or add a new appropriate model.

Image 1

With a subscription in place, we have the option to create a B2C Azure AD.

First, create a new tenant by clicking Azure Active Directory > Manage tenants > Create tenants. Complete the Organization name, Initial domain name, and Country/Region fields, then click Create to add the new tenant.

Image 2

The newly-created tenant appears on the Switch tenant page. Select the tenant and click Switch to work with that tenant.

Image 3

We must configure the Spring Boot application with the newly-created tenant’s details. So, move to the Application registration area, under the new AD tenant, and create a new registration. Provide a Name and select Accounts in any organizational directory and personnel Microsoft accounts for the account type.

Image 4

The console displays the client ID and tenant ID details after submission. Now we must provide a client secret for the application credentials. 

Go to the Certificates and Secrets area in the gsWeb app. Then, click New secret to generate the client secret. 

Azure AD returns JSON Web Tokens (JWTs) to the Spring application. So, we specify the application’s token exchange type and location.

We define a web app in the guestBook application and set the token return URL to http://localhost:8080/login/oauth2/code/. We put this token’s return path in the Java application to work with the authenticated token. Since we deploy the application on our localhosts, the return token path is http://localhost:8080. If you deploy the application on a domain name, be sure to change the location accordingly.

Additionally, we use the same application for the OpenID-based token exchange between Azure AD and the social platform. Therefore, we must specify a tenant-based URL (https://guestbooksocial.b2clogin.com/guestbooksocial.onmicrosoft.com/oauth2/authresp) to accept the validated tokens from the social platform. Make sure to replace the name with that of your B2C tenant. 

The Azure platform also enables us to validate this third-party platform integration from the browser. The validation process submits a token to a JWT service like http://jwt.ms. The service then renders the token details. So, add http://jwt.ms to the list of return URLs. Also, be sure to select both ID tokens and access tokens for identity information.

Image 5

Integrating Identity Providers

The Azure platform enables us to interface with most popular platforms, including Facebook, Google, Twitter, and Outlook. 

Let’s enable each of these platform integrations in the Azure AD tenant. Since we want to allow logging into Outlook and Skype in this application, add a Microsoft provider. The provider asks for the following details:

  • Name: provide a logical name. 
  • Client ID: provide the client ID for the app registration performed above. 
  • Client secret: give the secret generated for the Azure app.

Image 6

Enabling User Flows

After creating the identity provider, we must enable the application-specific data flows. The data flows allow users to perform several actions, including sign-up, sign-in, profile edits, and password resets. 

In the guestBook application, we only need a sign-up and sign-in flow, so click User flows and create a flow using the recommended configuration. The dialog additionally asks for the following details:

  • Name: use a logical name for the flow.
  • Accounts: select None to disallow any users created in the AD. 
  • Identity providers: select the newly-added Microsoft identity provider.
  • User Attributes: make sure to select the Return claim check box for Given Name as the attribute is in the token returned to the application.

Image 7

Verifying the Integration

As discussed previously, the Azure platform allows us to validate the integration.

To do so, open the newly-created user flow. It presents an option to run the flow. The action opens a dialog box asking you to select the return URL. Select the application and the http://jwt.ms URL that we added to the app return URLs.

Image 8

Click Run, and the browser opens a dialog box to provide credentials for your Microsoft platform accounts. After user validation, it returns the JWT access token and displays it in the jwt.ms console.

Image 9

Integrating the Application

Now that we have validated the Azure AD configuration, all that remains is integrating the guestBook application with the AD. We add dependencies for Azure B2C AD to configure authentication in the application.

XML
<dependency>
   <groupId>com.azure.spring</groupId>
   <artifactId>azure-spring-boot-starter-active-directory-b2c</artifactId>
   <version>3.9.0</version>
</dependency>

The Spring Boot starter requires the following additional parameters to connect to the correct Azure AD:

  • Base-URI: every B2C AD has a base URL that identifies the AD.
  • Client-Id: the client ID that the Azure AD application registration generates.
  • Client-secret: the client secret associated with the Azure AD application registration.
  • User flow: the name of the user flow we created in Azure AD.

We must provide these parameters as part of the application.properties file in the src/main/resources folder, like this:

# Azure AD properties
azure.activedirectory.b2c.base-uri: https://guestbooksocial.b2clogin.com/guestbooksocial.onmicrosoft.com/
azure.activedirectory.b2c.client-id: 3b94308a-fb95-4944-a5ec-e7536ecfb341
azure.activedirectory.b2c.client-secret: XXXXXX~XXXXXDni7LG_HUxWSVcG2Bn
azure.activedirectory.b2c.user-flows.sign-up-or-sign-in: B2C_1_gswebflow

Getting User Details

We enable authentication using the security annotation EnableWebSecurity. When we apply the annotation to a SecurityConfig class, we can customize and fine-tune security for our application’s needs.

Java
@EnableWebSecurity
public class AADOAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {


   private final AADB2COidcLoginConfigurer configurer;


   public AADOAuth2LoginSecurityConfig(AADB2COidcLoginConfigurer configurer) {
       this.configurer = configurer;
   }


   @Override
   protected void configure(HttpSecurity http) throws Exception {
       http
               .authorizeRequests()
               .anyRequest()
               .authenticated()
               .and()
               .apply(configurer)
       ;
   }
}

The adapter above uses the default redirect URI (/login/oauth2/code/). We can also customize this adapter by specifying the property azure.activedirectory.redirect-uri-template and configuring the OAuth processing location.

The above integration generates OAuth2AuthenticationToken, enabling us to read OAuth2 details. Since the above configuration allows this for all requests, we can modify the GET request to read the username from the principal rather than asking the user.

Java
@GetMapping({"/"})
public String loadBookEntry(Model model, OAuth2AuthenticationToken principal) {
   BookEntryDTO dto = new BookEntryDTO();
   dto.setName(principal.getPrincipal().getAttributes().get("name").toString());
   model.addAttribute("bookentry", dto);
   return "bookentry";
}

Now, start the application and access its URL. The application uses Microsoft-based authentication. You can log in using your Outlook.com or Skype credentials.

Image 10

Next Steps

You now know how to integrate with social platforms using Azure AD B2C seamlessly. The integration supports several platforms like Facebook, Twitter, Microsoft, and GitHub. We can use the identity exchange for more than the use cases of signing up and logging in. We can customize it to meet business needs.

Also, the Azure Spring Boot library provides concise integration with convention-based default values. It removes the hassle associated with the integration while enabling us to modify it as needed. Developers can focus on their business flows while leaving boilerplate integration to Azure AD and the associated Spring Boot starter library.

When you use Azure AD to integrate social logins into your application, your users enjoy an easier login experience while avoiding setting up yet another new account. Meanwhile, forcing a login helps keep your application and its data secure while enabling you to personalize the customer experience for each user.

Continue to the third article of this series to learn how to connect Azure AD with AWS Cognito for authentication in a multi-cloud environment.

To learn more about the evolution of the Azure Active Directory (Azure AD), check out The Developer's Guide to Azure.

This article is part of the series 'Connecting Azure Authentication to Other Providers View All

License

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


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Ștefan-Mihai MOGA12-Jan-22 4:54
professionalȘtefan-Mihai MOGA12-Jan-22 4:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.