首页 文章

Owin JWT 401未经授权

提问于
浏览
1

我正在尝试使用IdentityServer4和JWT进行身份验证 . 我从我的客户端获取一个令牌,并尝试向我的一个控制器发送一个简单的请求 .

我有这样的要求

GET api /用户授权:Bearer {}

在我的启动课程中,我已经注册了

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

我在每个 Console.WriteLine("Debugger") 陈述中都给出了破发点,但没有一个破发点被击中 . 我仍然未经授权返回 .

Headers 是否适合我的授权?我想在失败时查看请求,但即使启用了所有例外,我也无法达到突破点,是否有人有任何建议?

EDIT 我的客户配置:

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

控制器控制器基础:

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

    //...
}

1 回答

  • 1

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

    app.UseAuthentication();
    

相关问题