簡體   English   中英

未使用IdentityServer3承載令牌調用We​​bAPI授權屬性

[英]WebAPI Authorization Attribute not being called with IdentityServer3 Bearer Token

我有一個WebAPI 2項目,它使用IdentityServer3令牌提供程序發出的令牌。 在我的Startup.cs文件中,我實現了IdentityServerBearerTokenAuthorization中間件,它與全局AuthorizateAttribute過濾器一起要求請求中存在有效令牌。 但是,我還添加了ClaimsTransformation,因此我可以在使用隱式流發出的令牌或為客戶端憑據流發出的令牌中從聲明中提取“角色”。 我不能在這里使用范圍,因為我有1個范圍允許您訪問使用我的API,但不允許所有客戶端使用所有api端點。

Startup.cs

 JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();


        app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions()
        {
            Authority = ConfigurationManager.AppSettings["IdentityServer"],
            RequiredScopes = new[] { "my.api" },
        });



        httpConfig.MapHttpAttributeRoutes();
        httpConfig.Filters.Add(new AuthorizeAttribute());


        //SwaggerConfig.Register(httpConfig);

        app.UseAutofacMiddleware(container);
        app.UseAutofacWebApi(httpConfig);
        app.UseWebApi(httpConfig);

        app.UseClaimsTransformation(identity =>
        {
            var principal = new ClaimsPrincipal(identity);
            if (!identity.HasClaim(c => c.Type == "name") && identity.HasClaim(c => c.Type == "client_name"))
            {
                identity.Identities.First().AddClaim(new Claim("name", identity.Claims.First(c => c.Type == "client_name").Value));
            }

            //we want to remove the client_ from the claims so we can evaluate clients like they are users
            if (identity.Claims.Any(c => c.Type.Contains("client_")))
            {
                foreach (var claim in identity.Claims.Where(c => c.Type.Contains("client_")))
                {
                    var newClaimType = claim.Type.Replace("client_", "");
                    identity.Identities.First().AddClaim(new Claim(newClaimType, claim.Value));
                }
            }

            //set the scopes as roles also
            if (identity.Claims.Any(c => c.Type == "scope"))
            {
                identity.Identities.First().AddClaims(identity.Claims.Where(c => c.Type == "scope").Select(c => new Claim("role", c.Value)));
            }

            return Task.FromResult(principal);
        });

在我的APIController操作中,我有一個Authorize屬性,其中定義了Roles屬性。 全局Authorize屬性正在運行,但檢查角色永遠不會發生。 我錯過了什么嗎? \\ API控制器

    [HttpDelete]
    [Authorize(Roles = "item.deleter")]
    [Route("{itemId:guid}")]
    public async Task<HttpResponseMessage> DeleteAsync([ValidGuid] Guid itemId)
    {
        _log.Audit.Info($"Received Delete request for item {itemId} from user {User.Identity?.Name}.");
        if (!ModelState.IsValid)
      ....

您的authroize屬性很可能在聲明轉換觸發之前觸發。

在您的owin管道中,您在聲明轉換之前添加了webAPI。 隨着您的請求沿着管道傳輸,web api將獲得請求並在聲明轉換完成之前對其進行授權。

嘗試在UseClaimsTransformation之前移動UseWebApi

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM