.NET Core 2 - Web Api - Azure AD - User is NULL



我有一个 .NET Core 2.1 Web API 应用程序,其中我设置了用于身份验证的 Azure AD。对于我的授权,我正在使用一个基于用户名进行一些验证的AuthorizationHandler。我遇到的问题是User.Identity.Name总是返回null,我不确定为什么。

这是我设置身份验证和授权的Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors("AllowAnyOrigin");
app.UseAuthentication();
app.UseMvc();     
}
public void ConfigureServices(IServiceCollection services)
{
// Azure AD
services.AddAuthentication(
sharedOptions =>
{
sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(
options =>
{
options.Authority = "https://login.microsoftonline.com/" + "MyTenant";
options.Audience = "MyClientId";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = "https://login.microsoftonline.com/" + "MyTenant" +"/v2.0";
};
});
services.AddAuthorization(
options =>
{
options.AddPolicy("MyPolicy", policy => policy.Requirements.Add(new NameRequirement());
});
services.AddSingleton<IAuthorizationHandler, NameRequirementHandler>();
services.AddCors(options =>
{
options.AddPolicy("AllowAnyOrigin",
builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
services.Configure<MvcOptions>(options => {
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAnyOrigin"));
});

services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

在我的AuthorizationHandler中,我想获取经过身份验证的用户的名称,以便对其进行一些验证。我可以在请求中看到持有者令牌,但是User.Identity.Name和所有声明都null

public class NameRequirementHandler : AuthorizationHandler<NameRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, NameRequirement requirement)
{
var authorizationFilterContext = context.Resource as AuthorizationFilterContext;
if (authorizationFilterContext != null)
{
HttpContext httpContext = authorizationFilterContext.HttpContext;
string userName = httpContext.User.Identity.Name; // ALWAYS NULL
//Do some validation here with the user name value
}
context.Succeed(requirement);
return Task.CompletedTask;
}
}

目前,我有一个非常简单的控制器,用于测试身份验证和授权:

[Authorize(Policy = "MyPolicy")]
public class ValuesController
{
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
}

为了从持有者令牌填充用户信息,我缺少什么?为了添加更多上下文,我从.NET Framework移植它,它在那里工作,但它使用扩展方法UseWindowsAzureActiveDirectoryBearerAuthentication,这在.NET Core中不存在

这是它在.NET Framework中的样子

public void Configuration(IAppBuilder app)
{
var tokenValidation = new TokenValidationParameters
{
ValidAudience = "https://graph.windows.net/"
};
var authOptions = new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = "MyTenant",
TokenValidationParameters = tokenValidation,
MetadataAddress = ""
};
app.UseWindowsAzureActiveDirectoryBearerAuthentication(authOptions);
}

我已经看到了其他问题并阅读了许多文章,但仍然无法使其发挥作用。我的配置的哪一部分是错误的?

提前谢谢。

更新

我最终找到了这个问题的解决方案,受众值设置不正确。我没有设置令牌的"aud"值的受众值。您可以转到 https://jwt.ms 以查看令牌的声明,并确保设置了正确的受众群体。

您需要在 Configure 方法中调用 UseAuthentication,您可以在其中访问 IApplicationBuilder。会是这样的,

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseAuthentication(); // Make sure you've done this!
app.UseMvc();
}

从文档中,"将身份验证中间件添加到指定的 IApplicationBuilder,这将启用身份验证功能。

https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.authappbuilderextensions.useauthentication?view=aspnetcore-2.0

最新更新