简体   繁体   English

始终使用身份2中的不记名令牌获得“对此请求的授权已被拒绝”。

[英]Always get “Authorization has been denied for this request.” using Bearer tokens in Identity 2?

Using postman I can request a token, here it is: 使用邮递员,我可以请求令牌,这里是:

{
    "access_token": "N1FL606bmDkZyLplpkLAihaviMQhB042z-rhY262M_W5nSWIv8fDOQiYkEn6GCuDnrxpdOWBS7lpxlBazHYlwnP1RvpDFED1i_ml89QNspyGOWB6TcMkT1MmfUAZ617k9MNvl5UJh2jKzUwvDDeXMURG9tEtmE3UX2L2D-1VA9kqYOzOB1UYbpMAfdTi84jsbR0lhLkNkReQ5fqg4B3IFbbWNGWu5ONb1uuf00ixL-BIMqSvEaNn58_zCyAVFWVzcH2tayYTGT5p_AItKfYiWaYHKC0pDoZ_OBdlpB7Odc7ScwjwFM5vtpBZE81rpk8yjXnrTEk_j9n0eiloJnpWwA",
    "token_type": "bearer",
    "expires_in": 899,
    "refresh_token": "60da311d10f043b892c703c7fb7ab061",
    "as:client_id": "Erp",
    "userName": "bbauer",
    ".issued": "Tue, 30 Jun 2015 17:56:10 GMT",
    ".expires": "Tue, 30 Jun 2015 18:11:10 GMT"
}

I can also get information from an unprotected resource like so: http://localhost:60689/api/Accounts/User/bbauer 我还可以从不受保护的资源中获取信息,例如: http:// localhost:60689 / api / Accounts / User / bbauer

{
    "url": "http://localhost:60689/api/accounts/user/31",
    "id": 31,
    "userName": "bbauer",
    "fullName": "Brian Bauer",
    "email": null,
    "emailConfirmed": false,
    "roles": [
        "Administrator"
    ],
    "claims": []
}

From that I see that the user is in the "Administrator" role. 由此可见,该用户处于“管理员”角色。 When I try to get a protected resource, I ALWAYS get this back: "Authorization has been denied for this request." 当我尝试获取受保护的资源时,我总是会找回此信息: “此请求的授权已被拒绝。”

Here is the method in the controller: 这是控制器中的方法:

[Authorize(Roles = "Administrator")]
[Route("user/{id:int}", Name = "GetUserById")]
public async Task<IHttpActionResult> GetUser(int id)
{
    var user = await AppUserManager.FindByIdAsync(id);

    if (user != null)
    {
        return Ok(TheModelFactory.Create(user));
    }

    return NotFound();
}

Here are my settings in postman: http://localhost:60689/api/Accounts/User/31 这是我在邮递员中的设置: http:// localhost:60689 / api / Accounts / User / 31
Content-Type: application/json 内容类型: application / json
Accept: application/json 接受: application / json
Authorization: Bearer N1FL606bmDkZyLplpkLAihaviMQhB042z-rhY262M_W5nSWIv8fDOQiYkEn6GCuDnrxpdOWBS7lpxlBazHYlwnP1RvpDFED1i_ml89QNspyGOWB6TcMkT1MmfUAZ617k9MNvl5UJh2jKzUwvDDeXMURG9tEtmE3UX2L2D-1VA9kqYOzOB1UYbpMAfdTi84jsbR0lhLkNkReQ5fqg4B3IFbbWNGWu5ONb1uuf00ixL-BIMqSvEaNn58_zCyAVFWVzcH2tayYTGT5p_AItKfYiWaYHKC0pDoZ_OBdlpB7Odc7ScwjwFM5vtpBZE81rpk8yjXnrTEk_j9n0eiloJnpWwA 授权:承载N1FL606bmDkZyLplpkLAihaviMQhB042z-rhY262M_W5nSWIv8fDOQiYkEn6GCuDnrxpdOWBS7lpxlBazHYlwnP1RvpDFED1i_ml89QNspyGOWB6TcMkT1MmfUAZ617k9MNvl5UJh2jKzUwvDDeXMURG9tEtmE3UX2L2D-1VA9kqYOzOB1UYbpMAfdTi84jsbR0lhLkNkReQ5fqg4B3IFbbWNGWu5ONb1uuf00ixL-BIMqSvEaNn58_zCyAVFWVzcH2tayYTGT5p_AItKfYiWaYHKC0pDoZ_OBdlpB7Odc7ScwjwFM5vtpBZE81rpk8yjXnrTEk_j9n0eiloJnpWwA

I can use fiddler to verify the authorization header is being sent. 我可以使用提琴手来验证正在发送授权标头。 Another thing to note is when I pass the access_token in to get the unprotected /user/username resource, I can break in code and see the ClaimsPrincipal with these settings: 还要注意的另一件事是,当我传递access_token来获取不受保护的/ user / username资源时,我可以中断代码并使用以下设置查看ClaimsPrincipal:
AuthenticationType: Bearer AuthenticationType:承载
IsAuthenticated: true IsAuthenticated: true
Name: bbauer 姓名: bbauer

However, if I test User.IsInRole("Administrator") its always false. 但是,如果我测试User.IsInRole(“ Administrator”),则它始终为false。 Why is it false? 为什么是假的? The AspNetUserRole table has the entry, and when I fetch the user I see his one role of "Administrator"... what on God's green earth am I missing here? AspNetUserRole表具有该条目,当我获取用户时,我看到他的“管理员”角色……在这里,上帝的绿色世界上我想念的是什么?

Here is my Startup class if that helps: 这是我的启动类,如果有帮助的话:

public class Startup
{
    public static OAuthAuthorizationServerOptions OAuthServerOptions { get; private set; }
    public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }
    public static string PublicClientId { get; private set; }

    public void Configuration(IAppBuilder app)
    {
        var httpConfig = new HttpConfiguration();

        ConfigureOAuth(app);

        WebApiConfig.Register(httpConfig);

        app.UseCors(CorsOptions.AllowAll);
        app.UseWebApi(httpConfig);
    }

    public void ConfigureOAuth(IAppBuilder app)
    {
        // Configure the db context and user manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

        PublicClientId = "self";
        OAuthServerOptions = new OAuthAuthorizationServerOptions
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/Token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(15),
            Provider = new SimpleAuthorizationServerProvider(PublicClientId),
            RefreshTokenProvider = new SimpleRefreshTokenProvider(),
        };

        app.UseOAuthAuthorizationServer(OAuthServerOptions);

        OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
        app.UseOAuthBearerAuthentication(OAuthBearerOptions);
    }
}

It turns out I needed to add roles to my ClaimsIdentity in my SimpleAuthorizationServerProvider's GrantResourceOwnerCredentials method. 事实证明,我需要在SimpleAuthorizationServerProvider的GrantResourceOwnerCredentials方法中向我的ClaimsIdentity添加角色。 Here is the code (see commented section): 这是代码(请参阅注释部分):

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin") ?? "*";

    context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

    var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

    ApplicationUser user = await userManager.FindAsync(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("sub", context.UserName));

    //this loop is where the roles are added as claims
    foreach (var role in userManager.GetRoles(user.Id))
    {
        identity.AddClaim(new Claim(ClaimTypes.Role, role));
    }

    var props = new AuthenticationProperties(new Dictionary<string, string>
    {
        {
            "as:client_id", context.ClientId ?? string.Empty
        },
        {
            "userName", context.UserName
        }
    });

    var ticket = new AuthenticationTicket(identity, props);
    context.Validated(ticket);
}

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

相关问题 此请求已被拒绝授权。 总是 - Authorization has been denied for this request. Always 始终获得“此请求已被拒绝授权。”消息 - Always getting the “Authorization has been denied for this request.” message 此请求的授权已被拒绝。 邮差 - Authorization has been denied for this request. Postman 发送承载令牌时,API端点返回“此请求已拒绝授权。” - API end point returning “Authorization has been denied for this request.” when sending bearer token 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.” 此请求的授权已被拒绝:JWT承载 - Authorization has been denied for this request : JWT Bearer “消息”:“此请求已拒绝授权。”OWIN中间件 - “Message”: “Authorization has been denied for this request.” OWIN middleware 如何修改“此请求的授权已被拒绝。”使用过滤器HostAuthenticationFilter - How to Modify “Authorization has been denied for this request.” Using filter HostAuthenticationFilter 此请求的C#授权被拒绝 - C# Authorization has been denied for this request OAuth令牌授权(请求已被拒绝) - OAuth token authorization (request has been denied)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM