在.NET Core API上使用Azure AD对用户进行身份验证?

问题描述 投票:1回答:1

我正在.NET Core 2.0中编写一个API,需要从Azure AD获取jwt的详细信息。在我的操作中,我想访问用户身份对象以获取其用户名等。我尝试按以下方式执行此操作,但所有请求都以401响应。

public static IServiceCollection AddAzureAd(this IServiceCollection services, AzureAdOptions options)
{
    services.AddAuthentication(o =>
        {
            o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(o =>
        {
            o.Authority = options.Authority;
            o.Audience = options.Audience;
        });
    return services;
}

我使用的权威是“https://login.microsoftonline.com”,观众是“https://OURDOMAIN.onmicrosoft.com/OURAPPLICATIONNAME”。

我甚至尝试过以下并没有成功。

public static IServiceCollection AddAzureAd(this IServiceCollection services, AzureAdOptions options)
{
    var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("SECRET"));
    services.AddAuthentication(o =>
        {
            o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(o =>
        {
            o.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,
                ValidateAudience = false,
                ValidateIssuer = false
            };
            o.IncludeErrorDetails = true;
            o.Authority = options.Authority;
            o.Audience = options.Audience;
        });
    return services;
}
c# asp.net-core azure-active-directory
1个回答
0
投票

通过使用以下内容修复此问题。

services.AddAuthentication(o =>
{
    o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o =>
{
    o.Authority = options.AADInstance + options.TenantId;
    o.Audience = options.Audience;
    o.TokenValidationParameters = new TokenValidationParameters
    {
        ValidIssuer = $"{options.AADInstance}{options.TenantId}/v2.0"
    };
});
© www.soinside.com 2019 - 2024. All rights reserved.