我试图理解如何深入研究当我配置asp.net的地狱时我得到的自动化。我目前正在将一个小api从asp.net web-api 2翻译成asp.net核心。我不确定403在此配置中的来源或如何修复它。现在,大多数api端点只需要一个有效的令牌,而不需要检查令牌中的任何特定声明。因此,对于我所有经过身份验证的控制器,当使用有效的承载令牌时,我得到403响应,应该是200。此外,我现在使用非对称密钥与Auth0作为提供者。
Startup.cs配置方法I用于验证JWT承载令牌。
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
//Middleware added here order matters
//TODO formatter settings https://docs.asp.net/en/latest/mvc/models/formatting.html
//samples to check
//https://auth0.com/docs/server-apis/webapi-owin
//https://github.com/auth0-samples/auth0-aspnetcore-webapi-rs256
var options = new JwtBearerOptions
{
Audience = Configuration["auth0:clientId"]
,Authority = $"https://{Configuration["auth0:domain"]}/"
,Events = new JwtBearerEvents() // just a pass through to log events
};
app.UseJwtBearerAuthentication(options);
// Very hacky to catch invaild tokens https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/issues/191
// issue says the need for the required hack is fixed but it's been still happening. Issue about the fix https://github.com/aspnet/Security/issues/411
app.Use(next => async context => {
try
{
await next(context);
}
catch
{
// If the headers have already been sent, you can't replace the status code.
// In this case, throw an exception to close the connection.
if (context.Response.HasStarted)
{
throw;
}
context.Response.StatusCode = 401;
}
});
app.UseMvc();
// TODO global exception handling https://github.com/dotnet/corefx/issues/6398
app.UseSwaggerGen();
app.UseSwaggerUi();
}
}
答案 0 :(得分:0)
似乎您的令牌中间件未执行以验证传入的请求。 尝试将令牌中间件设置为自动运行。
var options = new JwtBearerOptions
{
//other configurations..
AutomaticAuthenticate = true;
};
您还可以使用属性在控制器中指定身份验证方案。
[Authorize(AuthenticationSchemes = "MyAuthenticationScheme")]
在此处详细了解:Limiting identity by scheme
答案 1 :(得分:0)
问题在于ConfigureServices部分中的策略。最简单的政策是我目前所需要的。
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc(c =>
{
// TODO implement this abstract class c.Filters.Add(typeof(ExceptionFilterAttribute));
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
c.Filters.Add(new AuthorizeFilter(policy));
c.Filters.Add(typeof(ValidateModelFilter));
});