OAuth 不记名令牌不起作用

OAuth bearer token not working

我有一个 auth-provider 的最小设置,它设置 claims-identity

public class SimpleAuthorizationProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        if (context.UserName != context.Password)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim("sub", context.UserName));
        identity.AddClaim(new Claim("role", "user"));

        context.Validated(identity);
    }
}

我正在尝试访问 hello-world-api,出现未授权访问错误。

public class HelloWorldApiController : ApiController
{

    [HttpGet]
    [Route("api/hello")]
    //[AllowAnonymous]
    [Authorize]
    public HttpResponseMessage FetchAllEnum()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "Hello World!!!");
    }
}

但我收到上述 API 的 401/未授权访问。我确实将不记名令牌返回给 web-api,并且我还将它作为 Bearer ABCD**** 传递给服务器。我确实看到在 Visual Studio.

中调试时设置了授权 header

如果我调试 AuthorizeAttribute,我得到 user.Identity.IsAuthenticated 作为 false,这实际上是导致问题的原因。 但是鉴于我确实看到了授权 header 集并且我已经在 OAuthProvider 中设置了声明详细信息,为什么 AuthorizeAttribute 没有读取该信息?

注意:这是一个 Web API 项目,因此没有对 MVC AuthorizeAttribute 的引用。

这是 OWIN 设置:

public static class WebApiConfig
{
    public static HttpConfiguration Register()
    {
        var config = new HttpConfiguration();
        config.MapHttpAttributeRoutes();
        //config.SuppressDefaultHostAuthentication(); //tried with/without this line
        config.Filters.Add(new AuthorizeAttribute());
        config.EnableCors(new EnableCorsAttribute("*", "*", "*", "*"));
        return config;
    }
}

public class OwinConfiguration
{
    // ReSharper disable once UnusedMember.Local
    public void Configuration(IAppBuilder app)
    {
        ConfigureOAuth(app);
        app.UseCors(CorsOptions.AllowAll);
        app.UseWebApi(WebApiConfig.Register());
    }

    private void ConfigureOAuth(IAppBuilder app)
    {
        var options = new OAuthAuthorizationServerOptions
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
            Provider = new SimpleAuthorizationProvider()
        };

        app.UseOAuthAuthorizationServer(options);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
}

要使其正常工作config.Filters.Add(new HostAuthenticationAttribute("bearer")); 需要在授权属性之前添加此行...

public static HttpConfiguration Register()
{
    var config = new HttpConfiguration();
    config.MapHttpAttributeRoutes();

    config.Filters.Add(new HostAuthenticationAttribute("bearer")); //added this
    config.Filters.Add(new AuthorizeAttribute());
    config.EnableCors(new EnableCorsAttribute("*", "*", "*", "*"));
    return config;
}

另一种对我有用的可能解决方案是不使用 HostAuthenticationAttribute,而是将 OWIN 过滤器设置为活动过滤器,如下所示:

var bearerOptions = new OAuthBearerAuthenticationOptions
{
    AccessTokenFormat = new JwtFormat(validationParameters),
    AuthenticationMode = AuthenticationMode.Active,
};