簡體   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