简体   繁体   English

使用 MSAL 验证不记名令牌(Azure 广告)

[英]Validate Bearer token (azure ad) with MSAL

I have a aspnet core 6 API and i need in my controller of API, validated the bearer token that with Microsoft Authentication Libraries (MSAL).我有一个 aspnet core 6 API,我需要在我的 API 控制器中使用 Microsoft 身份验证库 (MSAL) 验证不记名令牌。

I want verify in token, for example, my tenant or clientId.我想验证令牌,例如,我的租户或 clientId。

How i do this simple?我怎么做这个简单? I need add notation to verify, for example [AuthorizeMSAL]?我需要添加符号来验证,例如 [AuthorizeMSAL]?

Or i need to call "https://graph.microsoft.com" to validate token?或者我需要调用“https://graph.microsoft.com”来验证令牌?

Example my code:例如我的代码:

I receive an exception我收到一个例外

The provided value for scope offline_access openid profile is not valid.为范围 offline_access openid 配置文件提供的值无效。 Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).客户端凭证流必须有一个范围值,在资源标识符(应用程序 ID URI)后加上 /.default 后缀。

What you are looking for in here is the Microsoft Identity Platform, which does the job of handling Tokens and authorization in the Bakcend part ( .net web APIs ).您在这里寻找的是 Microsoft Identity Platform,它负责处理 Bakcend 部分(.net web API)中的令牌和授权。 In here I will suppose you have read and done the required configuration on the Azure portal, client app registration, Api registration, and exposing API (via scope or app roles ) if not please refer to the following docs for that.在这里,我假设您已经阅读并完成了 Azure 门户上所需的配置、客户端应用程序注册、Api 注册和公开 API (通过范围或应用程序角色) ,如果没有,请参阅以下文档

Then you will need to install Microsft.Identity.Web nuget package to be able to handle the token.In order to make use of the token you need to register the following authentication service to the container inside program.cs然后您需要安装Microsft.Identity.Web nuget 包才能处理令牌。为了使用令牌,您需要将以下身份验证服务注册到 program.cs 中的容器

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

At this point you should already have and AzureAd section in in your appsetting.json with details from you Azure AD configuration like mentioned below:此时,您的 appsetting.json 中应该已经有了 AzureAd 部分,其中包含 Azure AD 配置的详细信息,如下所述:

    {
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "ClientId": "Enter_the_Application_(client)_ID_here",
    "TenantId": "common",
    "Audience": "Enter_the_Application_ID_URI_here"
  },
}

If the configuration is done right in the Azure portal side and you have the correct credentials at your appsettings.json, you should be able to allow only authenticated users into a specific controller by adding the [Authorize] annotation above the controller definition.如果配置是在 Azure 门户端完成的,并且您在 appsettings.json 中拥有正确的凭据,您应该能够通过在控制器定义上方添加[Authorize]注释来仅允许经过身份验证的用户进入特定控制器。

You find here a link to the documentation mentioning all the steps, along with a sample that you can follow on.您可以在此处找到提及所有步骤的文档链接,以及您可以遵循的示例。 and this link contains more information about MSAL issued bearer token configuration and validation 此链接包含有关 MSAL 颁发的不记名令牌配置和验证的更多信息

I tried to reproduce the same in my environment and got the same error as below:我试图在我的环境中重现相同的内容并得到如下相同的错误:

在此处输入图像描述

The error usually occurs if the scope value is invalid while generating the token.如果在生成令牌时scope值无效,通常会发生该错误。

Note that, Client Credential Grant Type accepts scope with ./default or api://ClientId/.default only.请注意,Client Credential Grant Type 仅接受./defaultapi://ClientId/.default范围。

To resolve the error , use the parameters like below while generating the token:要解决该错误,请在生成令牌时使用如下参数:

https://login.microsoftonline.com/TenantID/oauth2/v2.0/token

client_id:ClientID
client_secret:ClientSecret
grant_type:client_credentials
scope:https://graph.microsoft.com/.default

Access token generated successfully like below:成功生成访问令牌,如下所示:

在此处输入图像描述

To validate the Bearer token, use the below sample code in your _Startup.cs_ file as mentioned in this MsDoc :要验证 Bearer 令牌,请在您的_Startup.cs_文件中使用以下示例代码,如本MsDoc中所述:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApi(Configuration);
services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
{
  var existingOnTokenValidatedHandler = options.Events.OnTokenValidated;
  options.Events.OnTokenValidated = async context =>
  {
       await existingOnTokenValidatedHandler(context);
            options.TokenValidationParameters.ValidIssuers = new[] { Issuers };
      options.TokenValidationParameters.ValidAudiences = new[] { valid};
  };
});

The Bearer token will be validated successfully like below: Bearer 令牌将被成功验证,如下所示:

在此处输入图像描述

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

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