我正在使用 Visual Studio 2015 Enterprise Update 1 和 ASP.NET vNext rc1-update1 来发布和使用 JWT 令牌,如 这里.
I am using Visual Studio 2015 Enterprise Update 1 and ASP.NET vNext rc1-update1 to issue and consume JWT tokens as described here.
在我们的实现中,我们希望控制令牌生命周期验证.
In our implementation we want to control token lifetime validation.
我们尝试了几种方法,所有这些方法都有不良副作用.例如,在一次尝试中,我们在 Configure 方法中接管了 TokenValidationParameters.TokenValidationParameters.LifetimeValidator 事件:
We tried several approaches, all of which had undesirable side effects. For example in one attempt we took over the TokenValidationParameters.TokenValidationParameters.LifetimeValidator event in the Configure method:
app.UseJwtBearerAuthentication
(
options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
LifetimeValidator = (DateTime? notBefore, DateTime? expires, SecurityToken securityToken, TokenValidationParameters validationParameters) =>
{
// Pretend to do custom validation
return false;
}
};
}
);
该事件导致验证失败,但客户端收到 500 错误,而我们希望返回 400 系列错误和一个小负载.
That event causes validation to fail as we'd like but the client receives a 500 error whereas we would like to return a 400-series error and a small payload instead.
在另一次尝试中,我们尝试了 TokenValidationParameters.Events 的各种实现,例如检查 ValidatedToken 事件中的声明,但发现我们无法阻止中间件调用控制器操作,除非引发异常,导致我们回到 500 错误问题.
In another attempt we tried various implementations of TokenValidationParameters.Events, such as inspecting claims in the ValidatedToken event but found we were unable to prevent the middleware from invoking the controller action short of throwing an exception which got us back to the 500 error problem.
所以我的问题是:
使用 OIDC 接管生命周期验证的最佳做法是什么?
What what is the best practices for taking over lifetime validation with OIDC?
我们是否可以强制 OIDC 不在令牌中包含某些生命周期声明,例如nbf",因为我们无论如何都不需要它们?
Can we force OIDC not to include certain lifetime claims in the token like "nbf" since we won't need them anyway?
此错误已在 ASP.NET Core RC2 中修复.不再需要此答案中描述的解决方法.
这是一个已知错误.遗憾的是,您可以在 beta8 中使用的解决方法 不再有效 在 RC1 中.
It's a known bug. Sadly, the workaround you could use in beta8 no longer works in RC1.
您唯一的选择是编写一个捕获异常的中间件,以防止服务器返回 500 响应.当然,它很丑陋,并且可能会隐藏重要的异常,但它是唯一适用于 RC1 的已知解决方法.
Your only option is to write a middleware catching the exception to prevent the server from returning a 500 response. Of course, it's ugly and will potentially hide important exceptions, but it's the only known workaround that works with RC1.
这是一个例子(确保在 JWT 承载中间件之前注册它):
Here's an example (make sure to register it before the JWT bearer middleware):
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;
}
});
这篇关于使用 AspNet.Security.OpenIdConnect.Server (ASP.NET vNext) 的自定义生命周期验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!