繁体   English   中英

发送承载令牌时,API端点返回“此请求已拒绝授权。”

[英]API end point returning “Authorization has been denied for this request.” when sending bearer token

我已经按照教程在C#中使用OAuth保护Web API。

我正在做一些测试,到目前为止,我已经能够从/token成功获得访问/token 我正在使用名为“高级REST客户端”的Chrome扩展程序对其进行测试。

{"access_token":"...","token_type":"bearer","expires_in":86399}

这是我从/token回来的。 一切都很好看。

我的下一个请求是我的测试API控制器:

namespace API.Controllers
{
    [Authorize]
    [RoutePrefix("api/Social")]
    public class SocialController : ApiController
    {
      ....


        [HttpPost]
        public IHttpActionResult Schedule(SocialPost post)
        {
            var test = HttpContext.Current.GetOwinContext().Authentication.User;

            ....
            return Ok();
        }
    }
}

该请求是一个POST并具有标头:

Authorization: Bearer XXXXXXXTOKEHEREXXXXXXX

我明白: Authorization has been denied for this request. 以JSON返回。

我也试过做一个GET,我得到了我所期望的,因为我没有实现它,所以不支持该方法。

这是我的授权提供商:

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

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {

        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        using (var repo = new AuthRepository())
        {
            IdentityUser user = await repo.FindUser(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
        }

        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
        identity.AddClaim(new Claim(ClaimTypes.Role, "User"));

        context.Validated(identity); 

    }
}

任何帮助都会很棒。 我不确定是请求还是代码错误。

编辑:这是我的Startup.cs

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var config = new HttpConfiguration();
        WebApiConfig.Register(config);
        app.UseWebApi(config);
        ConfigureOAuth(app);
    }

    public void ConfigureOAuth(IAppBuilder app)
    {
        var oAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new SimpleAuthorizationServerProvider()
        };

        // Token Generation
        app.UseOAuthAuthorizationServer(oAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

    }
}

问题很简单: 更改OWIN管道的顺序

public void Configuration(IAppBuilder app)
{
    ConfigureOAuth(app);
    var config = new HttpConfiguration();
    WebApiConfig.Register(config);
    app.UseWebApi(config);
}

对于OWIN管道顺序,您的配置非常重要。 在您的情况下,您尝试在OAuth处理程序之前使用Web API处理程序。 在其中,您验证您的请求,找到您的安全操作并尝试根据当前的Owin.Context.User进行验证。 此时此用户不存在,因为它的设置来自后来调用的OAuth Handler。

您必须使用此架构添加声明:

http://schemas.microsoft.com/ws/2008/06/identity/claims/role

最好的办法是使用预定义的声明集:

identity.AddClaim(new Claim(ClaimTypes.Role, "User"));

您可以在System.Security.Claims找到ClaimTypes

您需要考虑的另一件事是Controller / Action中的过滤器角色:

[Authorize(Roles="User")]

你可以找到一个简单的示例应用程序,自托管owin与jQuery的客户在这里

看起来与其他Owin程序集共存的“ System.IdentityModel.Tokens.Jwt”版本不合适。

如果您使用的是“Microsoft.Owin.Security.Jwt”2.1.0版,则应该使用版本3.0.2的“System.IdentityModel.Tokens.Jwt”程序集。

从包管理器控制台,尝试:

Update-Package System.IdentityModel.Tokens.Jwt -Version 3.0.2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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