简体   繁体   中英

WebAPI does not respect Jwt token for authorize attribute

I have implemented all the steps here and other tutorials at that site to issue and consume Jwt in my application using AngularJS and WebAPI. In my Startup.cs I am calling the following function to tell the app to consumer Jwt tokens when AuthorizeAttribute is present:

    private void ConfigureOAuthTokenConsumption(IAppBuilder app)
    {

        string issuer = MyIssuer;
        string audienceId = MyAudienceID;
        X509Certificate2 cert = GetMyCertificate();

        // Api controllers with an [Authorize] attribute will be validated with JWT
        app.UseJwtBearerAuthentication(
            new JwtBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                AllowedAudiences = new[] { audienceId },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new X509CertificateSecurityTokenProvider(issuer, cert)
                }
            });
    }

When I run the application I can login just fine, generate the Jwt tokens just fine, consume them in angular and add them to the API requests, but I still get a 404. I must be missing something in the Jwt configuration so that it is not being validated, but I'm not getting any errors.

Just for the heck of it I tried implementing a customer AuthorizeAttribute , and put a breakpoint in the IsAuthorized method. You can see that the request contains the Bearer token, but IsAuthorized returns false, and the Principal is not set.

Does anyone have an idea what I might be missing? I'm so close here.

I probably didn't have enough info in here to answer this properly, but it ended up being that I didn't submit my OWIN config statements in the right order. In Startup.cs I put app.UseWebApi(config); before the code that configured my authorization modules. Putting app.UseWebApi(config); at the end of the configuration code made it start working.

I posed this question better at the ASP.NET forums: http://forums.asp.net/p/2070482/5976299.aspx?p=True&t=635803483826595456

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM