简体   繁体   中英

Owin JWT 401 Unauthorized

I'm trying to authenticate using IdentityServer4 and JWT. I'm getting a token from my client and trying to post a simple request to one of my controllers.

I have a request like so

GET api/Users

Authorization: Bearer {{my-token}}

In my start up class I've registered

var authorizationPolicy = new AuthorizationPolicyBuilder()
         .RequireAuthenticatedUser()
         .Build();

services.AddMvc(config => {
    config.Filters.Add(new AuthorizeFilter(authorizationPolicy)});

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddIdentityServerAuthentication(o =>
{
    o.Authority = "https://localhost:44333";
    o.RequireHttpsMetadata = false;
    o.ApiName = "MyApi";
    o.JwtBearerEvents = new JwtBearerEvents
    {
        OnAuthenticationFailed = async context => {
            Console.WriteLine("Debugger");
        },
        OnMessageReceived = async context => {
            Console.WriteLine("Debugger");
        },

        OnTokenValidated = async tokenValidationContext =>
        {
            Console.WriteLine("Debugger");
        }
});

I've put break points at each one of the Console.WriteLine("Debugger") statements yet none of the break points hit. Still I'm returned an unauthorized.

Is the header proper for my authorization? I want to check the request when it fails, yet even with all exceptions turned on I cannot hit a break point, does anyone have any suggestions?

EDIT My Client Confiugration:

    public static IEnumerable<ApiResource> GetApiResources()
    {
        return new List<ApiResource>
        {
            new ApiResource("MyApi", "My Api"),
            new ApiResource
            {
                Name = "customAPI",
                DisplayName = "Custom API",
                Description = "Custom API Access",
                UserClaims = new List<string> {"role"},
                ApiSecrets = new List<Secret> {new Secret("secretPassword".Sha256())},
                Scopes = new List<Scope>
                {
                    new Scope("customAPI.read"),
                    new Scope("customAPI.write")
                }
            }
        };
    }

The controller controller base:

[Route("api/[controller]")]
public class AsyncCRUDSingleKeyServiceController<TDTO, TKey> : Controller
    where TKey : struct
{
    protected IAsyncCRUDService<TDTO> _service;

    public AsyncCRUDSingleKeyServiceController(IAsyncCRUDService<TDTO> service)
    {
        this._service = service;
    }

    [HttpGet("{id}")]
    public virtual async Task<TDTO> Get(TKey id)
    {
        return await this._service.Get(new object[] { id });
    }

    //...
}

在Startup.Configure中,您是否包括以下行(在app.UseMvc之前)?

app.UseAuthentication();

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