C# API端点返回“;此请求的授权已被拒绝。”;发送承载令牌时

C# API端点返回“;此请求的授权已被拒绝。”;发送承载令牌时,c#,oauth,asp.net-web-api2,owin,C#,Oauth,Asp.net Web Api2,Owin,我遵循了一个教程,在C#中使用OAuth保护Web API 我正在做一些测试,到目前为止,我已经能够成功地从/token获取访问令牌。我正在使用一个名为“高级REST客户端”的Chrome扩展来测试它 {"access_token":"...","token_type":"bearer","expires_in":86399} 这是我从/token得到的信息。一切看起来都很好 我的下一个请求是测试API控制器: namespace API.Controllers { [Authoriz

我遵循了一个教程,在C#中使用OAuth保护Web API

我正在做一些测试,到目前为止,我已经能够成功地从
/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
我得到:
此请求的授权已被拒绝。
以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());

    }
}

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

http://schemas.microsoft.com/ws/2008/06/identity/claims/role
最好使用预定义的声明集:

identity.AddClaim(new Claim(ClaimTypes.Role, "User"));
您可以在
System.Security.Claims
中找到
ClaimTypes

您必须考虑的另一件事是控制器/动作中的筛选器角色:

[Authorize(Roles="User")]
您可以找到一个简单的示例应用程序,即带有jquery客户端的自托管owin。

看起来像“System.IdentityModel.Tokens.Jwt”的版本,它与其他owin程序集共存是不正确的

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

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

Update-Package System.IdentityModel.Tokens.Jwt -Version 3.0.2
问题很简单: 更改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处理程序的令牌中设置的。

我添加了:
identity.AddClaim(新声明(ClaimTypes.Role,“user”)无效。用户是资本重要吗?在看到你的评论之前,我添加了这个。我不认为那有什么关系。我将查看您的链接。这是一个常量,可以是任何内容。我尝试更改
[Authorize]
以将角色包括在我的控制器中,但我仍然无法将其授权。我在角色“user”中创建了一个新用户,并成功地获得了一个新令牌。使用您建议的更改更新了上面的我的代码。如果您没有在管道中注册WebApi,您将如何执行此操作?我只是在使用默认的WebAPI模板。让请求正常工作,发布请求给我401。而令牌是一样的。这让我抓狂!谢谢你花时间发布这个答案。我在重构后浪费了几个小时试图找到这个问题的原因。天哪,我不会发布我浪费了几个小时试图找出这个问题,谢谢!