简体   繁体   English

如何使用 Azure Active Directory 在 ASP.NET Core 应用程序中获取经过身份验证的用户的名称

[英]How to get Name of Authenticated user in ASP.NET Core application using Azure Active Directory

In a ASP.NET Core application with Azure AD Connected and Configured.在 ASP.NET Core 应用程序中,已连接并配置 Azure AD。 I am able to get the NameIdentifier using this code:我能够使用此代码获取 NameIdentifier:

var user = User.FindFirst(ClaimTypes.NameIdentifier).Value; ✔️

When trying to get just a name with the following line of code:当尝试使用以下代码行获取名称时:

var user = User.FindFirst(ClaimTypes.Name).Value; ❌

I receive the following error:我收到以下错误:

Object reference not set to an instance of an object. Object 引用未设置为 object 的实例。

Looked up in Azure Active Directory the user does have a full first and last name.在 Azure Active Directory 中查找,用户确实有完整的名字和姓氏。 Tried many examples online, it looks like the name should be showing.在网上试了很多例子,看起来名字应该显示出来。

UPDATE:更新:

Finally figured it out, at first I managed to get all the human readable text like this:终于弄明白了,起初我设法得到了所有人类可读的文本,如下所示:

foreach (Claim item in User.Claims)
{
    if (item.Type.Contains("name"))
    {
      var username = item.Value;
    }
}

this is much better这个好多了

var userName = User.FindFirst("name").Value;

According to document : https://docs.microsoft.com/en-us/azure/architecture/multitenant-identity/claims :根据文件: https : //docs.microsoft.com/en-us/azure/architecture/multitenant-identity/claims

In ASP.NET Core, the OpenID Connect middleware converts some of the claim types when it populates the Claims collection for the user principal:在 ASP.NET Core 中,OpenID Connect 中间件在为用户主体填充 Claims 集合时会转换一些声明类型:

So that if the unique_name exists in ID token , the middleware will populate the value of ClaimTypes.Name .这样,如果 ID 令牌中存在 unique_name ,中间件将填充ClaimTypes.Name的值。 But according to document : Microsoft identity platform ID tokens :但根据文件: Microsoft 身份平台 ID 令牌

unique_name : Provides a human readable value that identifies the subject of the token. unique_name :提供标识令牌主题的人类可读值。 This value isn't guaranteed to be unique within a tenant and should be used only for display purposes.此值不能保证在租户中是唯一的,应仅用于显示目的。 Only issued in v1.0 id_tokens.仅在 v1.0 中发行 id_tokens。

So that the claim only issued in Azure AD V1.0 id tokens ,and it isn't guaranteed to be unique within a tenant .因此,声明仅在 Azure AD V1.0 id 令牌中发出,并且不保证在租户中是唯一的。

You can get the user's name and email by (The profile scope is required to receive the claims & test with Azure AD V2.0 app):您可以通过以下方式获取用户名和电子邮件(使用 Azure AD V2.0 应用程序接收声明和测试需要profile范围):

var userName = User.FindFirst("name").Value;
var Email = User.FindFirst("preferred_username").Value;

If you want to know the first name and last name of current user , you may acquire access token for Microsoft Graph , call user endpoint with token and check the givenName / surname values from response :如果您想知道当前用户的名字和姓氏,您可以获取 Microsoft Graph 的访问令牌,使用令牌调用用户端点并检查来自响应的givenName / surname值:

https://docs.microsoft.com/en-us/graph/api/user-get?view=graph-rest-1.0&tabs=http https://docs.microsoft.com/en-us/graph/api/user-get?view=graph-rest-1.0&tabs=http

I struggled with the same issue and found an example and it works very well:我遇到了同样的问题并找到了一个例子并且效果很好:

Basically:基本上:

 public WeatherForecastController(ILogger<WeatherForecastController> logger, ITokenAcquisition tokenAcquisition, GraphServiceClient graphServiceClient, IOptions<MicrosoftGraphOptions> graphOptions)
    {
        _logger = logger;
        _tokenAcquisition = tokenAcquisition;
        _graphServiceClient = graphServiceClient;
        _graphOptions = graphOptions;
    }

    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi);

        User user = _graphServiceClient.Me.Request().GetAsync().GetAwaiter().GetResult();

        _logger.LogInformation("User Id: " + user.Id.ToString());

This link will give the details on how to use it with Azure AD, .net web api, and angular此链接将详细介绍如何使用 Azure AD、.net web api 和 angular

active-directory-do.net-native-as.netcore-v2 活动目录-do.net-native-as.netcore-v2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 信号 R 将数据发送到 UI 的功能在 Angular/ASP.Net Core 中不起作用 web API 3.1 应用程序与 Azure 活动目录身份验证 - Signal R functionality to send data to UI not working in Angular/ASP.Net Core web API 3.1 application with Azure Active directory authentication ASP.NET 核心 - Azure 活动目录身份验证 - 无法从以下位置获取配置:'System.String' - ASP.NET Core - Azure Active directory Authentication - Unable to obtain configuration from: 'System.String' Asp.net Web Forms(非 MVC)azure 活动目录身份验证 - Asp.net Web Forms (NOT MVC) azure active directory authentication 如何从 .Net Frame Asp.Net 应用程序中的 Azure App Service 配置获取连接字符串? - How do I get a connection string from Azure App Service configuration in a .Net Frame Asp.Net application? 如果项目使用 Azure AD,当前用户 Id 是否可以在 ASP.NET Core 5 MVC controller 中访问? - Is the current user Id accessible in an ASP.NET Core 5 MVC controller if the project uses Azure AD? 有没有办法使用 Azure AD 令牌对 ASP.NET Core MVC controller 操作进行身份验证? - Is there a way to authenticate an ASP.NET Core MVC controller action using an Azure AD token? .NET 5 ASP.NET 核心应用程序未在 Azure 中启动 - .NET 5 ASP.NET Core App not starting in Azure 外部化身份验证时如何在 spring 引导中获取经过身份验证的用户(天蓝色) - How to get the authenticated user in spring boot when authentication is externalized (azure) Azure Active Directory:如何通过授权代码流 (MSAL) 获取用户的 object id? - Azure Active Directory: how to get user's object id via auth code flow (MSAL)? ASP.net 核心 docker https on Azure 应用服务容器 - ASP.net core docker https on Azure App Service Containers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM