API端点返回"此请求已拒绝授权".发送承载令牌时

Bri*_*tte 16 c# oauth owin asp.net-web-api2

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

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

{"access_token":"...","token_type":"bearer","expires_in":86399}
Run Code Online (Sandbox Code Playgroud)

这就是我从中得到的回报/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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请求是a POST并且具有标头:

Authorization: Bearer XXXXXXXTOKEHEREXXXXXXX
Run Code Online (Sandbox Code Playgroud)

我得到: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); 

    }
}
Run Code Online (Sandbox Code Playgroud)

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

编辑:这是我的 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());

    }
}
Run Code Online (Sandbox Code Playgroud)

And*_*hau 30

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

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

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