简体   繁体   中英

Get current logged user with AAD authentication provider

I have a simple website, hosted on Azure App Services, where I enabled AAD authentication following the express setting as recommended here and it is correctly working.

Now I would like to show on navigation bar the username / email of current logged in user. How should I do?

App is developed in C# Asp.Net Core 1.0.4

Thank you very much

You can use ClaimsPrincipal to get the identity.

from Azure Guide

 Claim displayName = ClaimsPrincipal.Current.FindFirst(ClaimsPrincipal.Current.Identities.First().NameClaimType);
ViewBag.DisplayName = displayName != null ? displayName.Value : string.Empty;

In a simple web site as you stated; make sure your controller is inheriting from Controller.

[Authorize]
public class MyController : Controller

And then simply use

protected string userName => User?.Identity?.Name ?? "Unnamed User";  

Then use use userName. It will return the AD user's login/email name

You are using Authentication and authorization in Azure App Service .

App Service passes user claims to your application by using special headers. External requests aren't allowed to set these headers, so they are present only if set by App Service. Some example headers include:

  • X-MS-CLIENT-PRINCIPAL-NAME
  • X-MS-CLIENT-PRINCIPAL-ID
  • X-MS-TOKEN-AAD-ID-TOKEN
  • X-MS-TOKEN-AAD-ACCESS-TOKEN

reference : https://docs.microsoft.com/en-us/azure/app-service/app-service-authentication-how-to#access-user-claims

Code that is written in any language or framework can get the information that it needs from these headers. For ASP.NET 4.6 apps, the ClaimsPrincipal is automatically set with the appropriate values.

Your application can also obtain additional details on the authenticated user by calling /.auth/me.

But currently seems ASP.NET Core does not support flowing identity info from an IIS module (like Easy Auth) to the app code . See discussion here .

I haven't test that in current days . But you can always get user's name , token information from above headers . If you want to get more user's claims , you can make a server-side request to the in-build endpoint /.auth/me to retrieve the claims .

You can write custom middlerware to populate the User property in .net Core :

https://stackoverflow.com/a/42270669/5751404

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM