需要帮助调试JwtSecurityTokenHandler(Web API身份验证/资源服务器) [英] Need help debugging JwtSecurityTokenHandler (web api owin auth / resource servers)

查看:814
本文介绍了需要帮助调试JwtSecurityTokenHandler(Web API身份验证/资源服务器)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我拼命试图找出为什么我不断从资源服务器收到401响应:

I am desperately trying to find out why I keep getting a 401 response from my resource server:

场景: 运行授权服务器的控制台程序. 运行资源服务器的控制台程序. 两者都使用的控制台程序(客户端).

Scenario: Console program running an authorization server. Console program running a resource server. Console program using both (client).

我毫无疑问地获得了令牌,并且它在jwt.io上以预期的内容进行了验证.此外,当提交用于创建令牌的base64编码机密时,该站点还将验证令牌字符串.

I have no problem getting the token, and it validates with expected content at jwt.io. Further, when submitting the base64 encoded secret used to create the token, the site also validates the token string.

我尝试了抑制和/或添加HostAuthentication默认值/过滤器的所有可能组合;我在auth和webapi use-calls之前和之后都使用过UseCors(AllowAll);我尝试过任何事情!

I have tried every possible combination of suppressing and/or adding HostAuthentication defaults/filters; I have used UseCors (AllowAll) before and after both auth and webapi use-calls; I have tried juuuuust about anything!

这是我的配置身份验证:

This is my configure auth:

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);
    }

这是我的Configuration和ConfigureWebApi:

and here is my Configuration and 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类),并且只是重写了我能做的所有事情,调用了基本操作.据我所知,默认实现没有任何问题读取令牌(所有期望值都在其中).

So, I tried to implement a custom JwtSecurityTokenHandler (testdumbass class) and just overrided everything I could, calling base operations. From what I can see, the default implementation has NO problem reading the token (all the expected values are there).

那么我该如何测试验证? 依次调用以下三种方法: 读令牌 CanReadToken ValidateToken(出validatedToken) *验证签名 * ReadToken * CanReadToken * ValidateIssuerSecurityKey *有效期 * ValidateAudience * ValidateIssuer * CreateClaimsIdentity ValidateToken完成

So how can I test the validation? The following three methods are called (in that order): ReadToken CanReadToken ValidateToken (out validatedToken) *ValidateSignature *ReadToken *CanReadToken *ValidateIssuerSecurityKey *ValidateLifetime *ValidateAudience *ValidateIssuer *CreateClaimsIdentity ValidateToken finishes

现在,out参数看起来很好.但是,SecurityKeys为0,Id为null(相关吗?) 内部的JwtSecurityToken有一个签名密钥,其中32字节的数组与我期望的匹配. 如果我查看非公开成员,则所有4个rawXXX字段均具有值(数据,标题和有效载荷符合预期(不知道rawSignature的内容)) 我使用" https://localhost 作为发行者,也可以从经过验证的令牌中读取.

Now the out parameter looks fine. SecurityKeys however are 0 and Id is null (any relevance?) The inner JwtSecurityToken has a signing key, where the 32 byte array matches what I would expect. If I look at non-public members allthe 4 rawXXX field have values (Data, Header and Payload as expected (dunno what to make of rawSignature)) I am using "https://localhost" as issuer, which can also be read from the validated token.

所有这些之后,我在自己的自定义AuthorizeAttribute中覆盖了OnAuthorizationAsync.在这里,我称其为基本实现(AuthorizeAttribute中的一个),而actionContext始终以401失败.

After all of this, I have overriden OnAuthorizationAsync in my own custom AuthorizeAttribute. Here I call the base implementation (the one in AuthorizeAttribute) and the actionContext always fails with 401.

我必须承认我真的无法弄清楚为什么!

I must admit I really cannot figure out WHY!

推荐答案

我发现了问题所在:

我从这里接了这两行:

private void ConfigureAuth(IAppBuilder app, HttpConfiguration config)
{
    config.SuppressDefaultHostAuthentication();
    config.Filters.Add(new HostAuthenticationFilter("Bearer"));

并将其移到此处:

private void ConfigureWebApi(HttpConfiguration config)
{
    config.SuppressDefaultHostAuthentication();
    config.Filters.Add(new HostAuthenticationFilter("Bearer"));
    config.MapHttpAttributeRoutes();

这将在AuthorizeAttribute验证中(在作为参数发送的HttpActionContext中)产生具有正确身份的正确上下文.

This would result in the correct context with correct identity in the AuthorizeAttribute validation (in the HttpActionContext sent as parameter).

我不明白,为什么在UseWebApi调用中使用配置之前更改配置很重要?

What I dont get, is why changes in the config matter before using it in the UseWebApi call?

这篇关于需要帮助调试JwtSecurityTokenHandler(Web API身份验证/资源服务器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆