简体   繁体   English

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

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

I've followed a tutorial to protect a Web API with OAuth in C#. 我已经按照教程在C#中使用OAuth保护Web API。

I'm doing some tests and so far I've been able to get the access token successfully from /token . 我正在做一些测试,到目前为止,我已经能够从/token成功获得访问/token I'm using a Chrome extension called "Advanced REST Client" to test it. 我正在使用名为“高级REST客户端”的Chrome扩展程序对其进行测试。

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

This is what I get back from /token . 这是我从/token回来的。 Everything looks good. 一切都很好看。

My next request is to my test API Controller: 我的下一个请求是我的测试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();
        }
    }
}

The request is a POST and has the header: 该请求是一个POST并具有标头:

Authorization: Bearer XXXXXXXTOKEHEREXXXXXXX

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

I tried doing a GET as well and I get what I would expect, that the method isn't supported since I didn't implement it. 我也试过做一个GET,我得到了我所期望的,因为我没有实现它,所以不支持该方法。

Here is my Authorization Provider: 这是我的授权提供商:

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

    }
}

Any help would be great. 任何帮助都会很棒。 I'm not sure if it is the request or the code that is wrong. 我不确定是请求还是代码错误。

edit: Here is my Startup.cs 编辑:这是我的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());

    }
}

Issue is pretty simple: Change order of your OWIN pipeline . 问题很简单: 更改OWIN管道的顺序

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

For OWIN pipeline order of your configuration quite important. 对于OWIN管道顺序,您的配置非常重要。 In your case, you try to use your Web API handler before the OAuth handler. 在您的情况下,您尝试在OAuth处理程序之前使用Web API处理程序。 Inside of it, you validate your request, found you secure action and try to validate it against current Owin.Context.User . 在其中,您验证您的请求,找到您的安全操作并尝试根据当前的Owin.Context.User进行验证。 At this point this user not exist because its set from the token with OAuth Handler which called later. 此时此用户不存在,因为它的设置来自后来调用的OAuth Handler。

You have to add a claim with this schema: 您必须使用此架构添加声明:

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

best thing to do is to use the pre-defined set of claims: 最好的办法是使用预定义的声明集:

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

You can find ClaimTypes in System.Security.Claims . 您可以在System.Security.Claims找到ClaimTypes

Another thing you have to consider is filter roles in your Controller/Action: 您需要考虑的另一件事是Controller / Action中的过滤器角色:

[Authorize(Roles="User")]

You can find a simple sample app, self-hosted owin with a jquery client here . 你可以找到一个简单的示例应用程序,自托管owin与jQuery的客户在这里

Looks like the version of " System.IdentityModel.Tokens.Jwt" that co-exists with the other Owin assemblies is not proper. 看起来与其他Owin程序集共存的“ System.IdentityModel.Tokens.Jwt”版本不合适。

In case you're using "Microsoft.Owin.Security.Jwt" version 2.1.0, you ought to be using the "System.IdentityModel.Tokens.Jwt" assembly of version 3.0.2. 如果您使用的是“Microsoft.Owin.Security.Jwt”2.1.0版,则应该使用版本3.0.2的“System.IdentityModel.Tokens.Jwt”程序集。

From the package manager console, try: 从包管理器控制台,尝试:

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

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

相关问题 Azure AD 带有用于 Web API 的不记名令牌身份验证的 AD 无法正常工作,抛出错误,因为“此请求的授权已被拒绝”。 - Azure AD with Bearer token authentication for Web API not working throwing error as “Authorization has been denied for this request.” 此请求已被拒绝授权。 总是 - Authorization has been denied for this request. Always 此请求的授权已被拒绝。 邮差 - Authorization has been denied for this request. Postman 始终使用身份2中的不记名令牌获得“对此请求的授权已被拒绝”。 - Always get “Authorization has been denied for this request.” using Bearer tokens in Identity 2? 此请求的授权已被拒绝:JWT承载 - Authorization has been denied for this request : JWT Bearer “消息”:“此请求已拒绝授权。”OWIN中间件 - “Message”: “Authorization has been denied for this request.” OWIN middleware 始终获得“此请求已被拒绝授权。”消息 - Always getting the “Authorization has been denied for this request.” message OAuth令牌授权(请求已被拒绝) - OAuth token authorization (request has been denied) httpclient令牌对此请求的授权已被拒绝 - httpclient token Authorization has been denied for this request 如何修改“此请求的授权已被拒绝。”使用过滤器HostAuthenticationFilter - How to Modify “Authorization has been denied for this request.” Using filter HostAuthenticationFilter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM