添加对Windows身份的声明

时间:2016-08-28 15:16:29

标签: authentication asp.net-web-api asp.net-core authorization asp.net-core-mvc

我正在尝试为Windows Authentication项目的Asp.net Core Webapi分配角色。以下是我通过添加角色声明当前身份进行转换。

public class ClaimsTransformer : IClaimsTransformer
    {
        public Task<ClaimsPrincipal> TransformAsync(ClaimsTransformationContext context)
        {
            //add new claim
            var ci = (ClaimsIdentity) context.Principal.Identity;
            var c = new Claim(ClaimTypes.Role, "admin");
            ci.AddClaim(c);

            return Task.FromResult(context.Principal);
        }
    }

此中间件已添加到Startup.Configure:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
      {
          loggerFactory.AddConsole(LogLevel.Debug);
          loggerFactory.AddDebug();

          app.UseClaimsTransformation(o => new ClaimsTransformer().TransformAsync(o));

          app.UseStaticFiles();

          app.UseMvc();
      }

但是此方法未授权角色admin(403-Forbidden)。

[Route("api/[controller]")]
    public class ValuesController : Controller
    {        
        // GET api/values/5
        [HttpGet("{id}")]
        [Authorize(Roles = "admin")]
        public string Get(int id)
        {
            return "value";
        }
    }

如果使用[Authorize],它可以正常工作。有没有?

1 个答案:

答案 0 :(得分:2)

不幸的是,User.IsInRole方法不能使用ClaimsTransformer(如果使用ClaimsTransformer添加角色,IsInRole将为false),因此您无法使用[授权(角色=&#34;&#34; )]使用ClaimsTransformer。在这种情况下,您可以使用基于声明的授权来处理自动调整。

因此,将以下代码添加到ConfigureServices并使用Authorize属性:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddAuthorization(options =>
    {
        options.AddPolicy("admin", policy => policy.RequireClaim(ClaimTypes.Role, "admin"));
    });
    //...
}


[Route("api/[controller]")]
public class ValuesController : Controller
{        
    // GET api/values/5
    [HttpGet("{id}")]
    [Authorize(Policy = "admin")]
    public string Get(int id)
    {
        return "value";
    }
}
相关问题