Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add and access additional properties once logged in using Azure Active Directory in MVC?

I have setup an Azure Active Directory (AD) to log in an MVC Web application. Once logged in, only Email ID is returned from Azure. I need to extend this to get some basic properties using Email ID as a key field; to map AD and my database which contains additional details.

My requirements are below

  1. Need to use AD for login.
  2. Once logged in Azure will return Email ID (which can be accessed from HttpContext.User.Identity.Name) I need to fetch some additional profile related properties from my Database during login time and store in extended identity.
  3. I don't want to fetch these additional details every time from Database on each action execution, instead, I need to get those additional properties from my DB after user logged in as like MVC normal authentication.
  4. AD Graph API is not useful because I don't want to store additional details in Azure instead it will be available in my Database.
like image 866
Bharat Avatar asked Nov 08 '22 02:11

Bharat


1 Answers

If you are using the OWIN middleware for OpenIdConnect, you can add your custom data as custom claims after the middleware has validated the token.

So something like:

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
  // Rest of config left out for brevity
  Notifications = new OpenIdConnectAuthenticationNotifications
  {
    SecurityTokenValidated = async (notification) =>
    {
      ClaimsIdentity identity = notification.AuthenticationTicket.Identity;
      //Get the user data any way you want
      //Add claims
      identity.AddClaim(new Claim("homeTown", "Somewhere"));
    }
  }
});

The ClaimsIdentity will contain the usual user information about the signed-in user. You can add any claims you want here, and they will be stored the same as the usual ones. You can then access these claims e.g. in your controllers through the User property, or through ClaimsPrincipal.Current anywhere else.

The main advantage here is that you only fetch the data once when the user signs in, you don't need to get them on each request.

like image 111
juunas Avatar answered Nov 14 '22 20:11

juunas