【发布时间】:2018-02-05 19:32:03
【问题描述】:
我正在 .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;
}
【问题讨论】:
-
这个
o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;是错误的。只需使用.UseAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) -
@CamiloTerevinto 我发布了一个旧代码 sn-p,请立即查看。你给我的代码抛出了异常“没有指定 authenticationScheme,也没有找到 DefaultChallengeScheme。”
-
如果您查看 ASP.NET Core 生成的日志,您没有看到无效的 issuer 消息吗?我必须添加到
options.TokenValidationParameters.ValidIssuers:https://sts.windows.net/ID和https://login.microsoftonline.com/ID,其中 ID 是域的 ID。有一个option.可以启用详细的错误消息 -
@CamiloTerevinto 我唯一能看到的是“Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization failed for user: (null).”在输出窗口中。
-
您是否在
ConfigureServices和app.UseAuthentication().UseMvc()中添加了services.AddMvc()Configure?
标签: c# asp.net-core azure-active-directory