简体   繁体   English

此请求被拒绝获得授权

[英]Getting Authorization has been denied for this request

I have configured my Web API 2 project to work with OAuth using OWIN 我已经将我的Web API 2项目配置为使用OWIN与OAuth一起使用

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureOAuth(app);

            HttpConfiguration config = new HttpConfiguration();
            WebApiConfig.Register(config);
            app.UseWebApi(config);
        }

        public void ConfigureOAuth(IAppBuilder app)
        {

            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {

                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new MyAuthorizationServerProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

        }

    }

The implementation of MyAuthorizationServerProvider: MyAuthorizationServerProvider的实现:

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

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var repo = new AuthRepository();
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        var user = repo.ValidateUserCredentials(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("sub", context.UserName));
        identity.AddClaim(new Claim("role", "user"));

        context.Validated(identity);
    }
}

I am able to get a Token.. then i send it to a controller decorated with [Authorized] and still getting 我能够获得令牌。然后将其发送到装饰有[Authorized]的控制器,仍然

{
  "message": "Authorization has been denied for this request."
}

The request headers with token here: 带有令牌的请求标头:

Content-Type:application/json
Authorization:Bearer m6ukGHOmp_MgM6rsb70n8Rd_BlBEXbgyPNr5ZNzGzkm__7zdntVPYAMAhFPXVdw1S6-ohv960c6mzMMwkY0G_AL-2uIq2aOjkoojxDPKuITuml8sgC4ng0KC2AqUFrBBEn0eCsSAnc3UK_jyKSB59Ao_eL9JPoJHoJHP-xBs42KGAGl4iKdYtzdfg2zY0Ucif_IpPH3Gbvs6iyLVMf0jlKgj4EOBtrDHanikeqkWc0W2pWjIIac8cyUrOtZCj7h3

What am I doing wrong here ? 我在这里做错了什么?

Also .. wonder.. where is the token stored ? 另外..奇迹..令牌存储在哪里? how can Web API validate the the received token is attached to the user in question ? Web API如何验证收到的令牌已附加到相关用户?

Am I missing a custom implementation of some token store class ? 我是否缺少某些令牌存储类的自定义实现? if so where can I find information on how to implement a custom token store ? 如果是这样,我在哪里可以找到有关如何实现自定义令牌存储的信息?

The token is not stored anywhere, it's just an encoded bit of data and you can extract the info from it when you receive it on the other side. 令牌没有存储在任何地方,它只是数据的编码位,当您在另一侧收到令牌时,可以从令牌中提取信息。

The validation happens inside the ValidateClientAuthentication method. 验证发生在ValidateClientAuthentication方法内部。 You've just set the context to authenticated with no checks at all. 您只需将上下文设置为经过身份验证,而无需进行任何检查。 This is where you check the ClientID / Client Secret combination is correct, the name indicates that as well. 在此处检查ClientID / Client Secret组合是否正确,名称也表明正确。 You can add extra stuff in there. 您可以在其中添加其他内容。

I personally don't use OAuth2 for user level authentication but nothing stops you from doing that if that's what you need. 我个人不使用OAuth2进行用户级身份验证,但是如果您需要的话,没有什么可以阻止您这样做。 I prefer to keep the token application related, not user related, but that's just my preference. 我宁愿保持令牌应用程序相关,而不是与用户相关,但这只是我的偏爱。

GrantResourceOwnerCredentials sets a context error on invalid_grant? GrantResourceOwnerCredentials在invalid_grant上设置上下文错误? The grant has nothing to do with the username / password you're trying to pass through. 授予与您尝试通过的用户名/密码无关。 You only set the grant_type when you request the token and it's usually of type password. 您仅在请求令牌时设置grant_type,并且通常为password类型。 invalid_grant means you're trying a different grant type and that's not clear from your code at all. invalid_grant表示您正在尝试使用其他授予类型,而代码中并不清楚。

You also haven't shown us your token format class, how you create it, what info you put in it, etc. 您也没有向我们显示您的令牌格式类,如何创建它,输入了什么信息等等。

Also, one thing I've noticed you're using both 另外,我注意到您同时使用这两种方法

UseOAuthBearerAuthentication - with empty options and also UseOAuthAuthorizationServer. UseOAuthBearerAuthentication-具有空选项以及UseOAuthAuthorizationServer。

The last one should be enough I would think. 我认为最后一个应该足够了。 I've used JWT when using OAuth2 but it doesn't look like you're actually using it. 在使用OAuth2时,我已经使用过JWT,但实际上您似乎并没有使用它。 The code looks a bit all over the place to be honest. 说实话,代码看起来到处都是。

I wonder if you'd mind creating a repo with just enough code to replicate the issue. 我想知道您是否介意使用足够的代码来创建仓库来复制问题。

I will try to have a look tonight, see if I can replicate the issue. 今晚我将尝试看看,看看是否可以复制该问题。 You're welcome to hit me up on Twitter later on today. 欢迎您今天晚些时候在Twitter上与我联系。

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

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