【发布时间】:2016-10-14 11:57:34
【问题描述】:
我试图了解如何深入研究当我从 asp.net 配置地狱时获得的自动魔法。我目前正在将一个小的 api 从 asp.net web-api 2 转换为 asp.net core。我不确定 403 在此配置中来自何处或如何修复它。现在大多数 api 端点只需要一个有效的令牌,不需要检查令牌中的任何特定声明。因此,对于我所有经过身份验证的控制器,当使用有效的不记名令牌时,我会收到一个 403 响应,该响应应该是 200。现在我也使用 Auth0 作为提供者的非对称密钥。
我用来验证 JWT 不记名令牌的 Startup.cs 配置方法。
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();
}
}
【问题讨论】:
标签: c# asp.net-core openid jwt