首页 > 解决方案 > 401 使用 Azure AD 在 .NET Core 3.1 中仅使用不记名令牌进行身份验证

问题描述

我正在尝试使用 Azure AD 在 .NET Core 3.1 API 中实现不记名令牌(仅)身份验证。

验证后,我可以从 Azure AD 检索令牌,authorization_code并且浏览器使用以下内容回发到我的重定向 URL:

{"token_type":"Bearer","scope":"User.Read","expires_in":3600,"ext_expires_in":3600,"access_token":"EwBwA8l6...SzT3qoxGbSMg=="}(缩短)

拥有此令牌后,我是否可以[Authorize]直接在我的 API 上使用该属性并在标头中使用 Bearer 令牌进行请求?当我这样做时,我会收到 401 响应。

我有这个ConfigureServices()

services.AddAuthentication(options =>
{
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.Audience = "<guid>";

    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
    {
        ValidateIssuerSigningKey = false,
        ValidateAudience = false,
        ValidateIssuer = false,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("abc123")),
        TokenDecryptionKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("abc123"))
    };
});
services.AddControllers();

Configure()我有:

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});

在我的错误日志中,我看到的消息是:

“承载者”未通过身份验证。失败消息:“没有可用于令牌的 SecurityTokenValidator

我在 Startup.cs 中尝试了很多很多设置组合,无论如何,从 Postman 调用我的 API 时,我似乎只能得到 401。我可以使用我在网上找到的代码示例进行 Cookie 身份验证,但我不希望这样。

是令牌被加密的问题吗?我是否尝试使用错误的令牌?还是有其他问题?我是否需要在我的应用程序中使用 AspNetUser 等的数据库表设置身份?

简而言之,我只是尝试使用 Azure AD 作为身份验证提供程序生成承载令牌,并通过传入承载令牌标头来调用我的 API。

标签: asp.net-coreauthenticationoauth-2.0jwtazure-active-directory

解决方案


看起来有点像您正在尝试在 API 中使用 Microsoft Graph API 令牌。(基于此"scope":"User.Read":)

您的前端应用程序需要为您的 API 使用范围,而不是 User.Read。这样,它将获得一个用于您的 API 的访问令牌。通过公开 API 部分在您的 API 应用注册上注册一个范围,并在获取令牌时在您的前端使用完整的范围值。

您的后端需要以下配置:

.AddJwtBearer(options =>
{
    // add v2.0 to the end if your API is set to get v2 tokens in its manifest
    options.Authority = "https://login.microsoftonline.com/your-aad-tenant-id";
    options.Audience = "your-api-client-id";
});

这应该是身份验证所需的最低配置。它会在启动时自动从权威机构查找签名密钥等。


推荐阅读