我正在.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;
}
答案 0 :(得分: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"
};
});