【发布时间】:2016-03-12 07:35:11
【问题描述】:
我正在拼命想找出为什么我不断从我的资源服务器收到 401 响应:
场景: 运行授权服务器的控制台程序。 运行资源服务器的控制台程序。 使用两者的控制台程序(客户端)。
我在获取令牌时没有问题,它通过 jwt.io 上的预期内容进行验证。此外,在提交用于创建令牌的 base64 编码密钥时,网站还会验证令牌字符串。
我已经尝试了抑制和/或添加 HostAuthentication 默认值/过滤器的所有可能组合;我在 auth 和 webapi 使用调用之前和之后都使用了 UseCors (AllowAll);我已经尝试过任何事情!
这是我的配置验证:
private void ConfigureAuth(IAppBuilder app, HttpConfiguration config)
{
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter("Bearer"));
var issuer = ConfigurationManager.AppSettings["tokenIssuer"];
var audience = "MyEnergy"; //TODO: audience should be taken from somewhere else!!
var secret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["secret"]); //TODO: no configuration manager here!
var jwtBearerOptions = new JwtBearerAuthenticationOptions()
{
TokenHandler = new testdumbass(),
AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
AuthenticationType = "JWT",
AllowedAudiences = new[] {audience},
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)}
};
app.UseJwtBearerAuthentication(jwtBearerOptions);
}
这是我的配置和 ConfigureWebApi:
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
ConfigureAuth(app, config); //using oauth
ConfigureWebApi(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
private void ConfigureWebApi(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
"Default",
"{controller}/{id}",
new {id = RouteParameter.Optional});
}
所以,我尝试实现一个自定义 JwtSecurityTokenHandler(testdumbass 类),并且只是覆盖了我所能做的一切,调用基本操作。据我所知,默认实现读取令牌没有问题(所有预期值都在那里)。
那么我该如何测试验证呢? 调用以下三个方法(按此顺序): 读取令牌 CanReadToken ValidateToken(出验证令牌) *验证签名 *读取令牌 *CanReadToken *ValidateIssuerSecurityKey *验证生命周期 *验证观众 *验证发行人 *CreateClaimsIdentity ValidateToken 完成
现在 out 参数看起来很好。然而,SecurityKeys 为 0 并且 Id 为空(任何相关性?) 内部 JwtSecurityToken 有一个签名密钥,其中 32 字节数组符合我的预期。 如果我查看非公共成员,所有 4 个 rawXXX 字段都有值(数据、标头和有效负载符合预期(不知道如何使用 rawSignature)) 我使用“https://localhost”作为颁发者,也可以从经过验证的令牌中读取。
在这一切之后,我已经在我自己的自定义 AuthorizeAttribute 中覆盖了 OnAuthorizationAsync。在这里,我调用了基本实现(AuthorizeAttribute 中的那个),而 actionContext 总是以 401 失败。
我必须承认我真的不知道为什么!
【问题讨论】:
-
我现在发现,问题不在于令牌处理程序。它确实创建了一个已验证的 ClaimsIdentity。但是,这不是我在创建自己的派生 AuthorizaAttribute 时可以从 HttpActionContext 检索的 ClaimsIdentity。
-
我想我现在可以得出结论,在 JWT 不记名身份验证结束后,owin 管道中没有进行任何操作。我已经花了一个多星期的时间来试验这个,我只是看不到任何让 JWT 令牌与 owin 自托管 wep api 2 一起使用的方法。我似乎也是这个星球上唯一一个尝试这样做的人,因为每个示例要么是身份验证/资源服务器合二为一,要么托管在 IIS 中或南希。
标签: asp.net-web-api2 owin jwt