未使用IdentityServer3承载令牌调用We​​bAPI授权属性

时间:2017-03-25 02:48:43

标签: c# asp.net-web-api identityserver3

我有一个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)
      ....

1 个答案:

答案 0 :(得分:2)

您的authroize属性最有可能在声明转换之前触发。

在您的owin管道中,您已在声明转换之前添加了webAPI。随着您的请求沿着管道传输,web api将获得请求&amp;在声明转换可以做到这一点之前运行授权。

尝试在UseClaimsTransformation

之前移动UseWebApi