OAuth承载令牌无效

har*_*shr 8 c# oauth asp.net-web-api owin bearer-token

我有一个auth-provider的最小设置,它设置了声明身份

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试访问hello-world-api,这会给出未经授权的访问错误.

public class HelloWorldApiController : ApiController
{

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

但我正在获得上述API的401 /未经授权的访问权限.我确实将持有者令牌返回到web-api,我也将它传递给服务器Bearer ABCD****.我确实看到在Visual Studio中调试时设置了授权标头.

如果我调试AuthorizeAttribute,我得到user.Identity.IsAuthenticatedfalse,这实际上导致了问题.但鉴于我确实看到了Authorization标头集并且我已设置了声明详细信息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());
    }
}
Run Code Online (Sandbox Code Playgroud)

har*_*shr 5

要使其工作config.Filters.Add(new HostAuthenticationAttribute("bearer"));需要添加此行beofre authorize属性...

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;
}
Run Code Online (Sandbox Code Playgroud)


r59*_*590 1

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

var bearerOptions = new OAuthBearerAuthenticationOptions
{
    AccessTokenFormat = new JwtFormat(validationParameters),
    AuthenticationMode = AuthenticationMode.Active,
};
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

6510 次

最近记录:

8 年,6 月 前