add claims to windows identity

牧云@^-^@ 提交于 2019-12-12 02:37:58

问题


I am trying to assign roles as claims for Windows Authentication for Asp.net Core Webapi project. Below is my transform by adding a role claim current identity.

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);
        }
    }

And this middleware is added to 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();
      }

However role admin is not authorized in this method (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";
        }
    }

It is working properly if [Authorize] is used. Any missing?


回答1:


Unfortunately User.IsInRole method doesn't work with ClaimsTransformer(if you add role with ClaimsTransformer, IsInRole will be false) so you can't use [Authorize(Roles = "")] with ClaimsTransformer. In this case you can use Claims Based Authorization to handle authotorization.

So add below code to ConfigureServices and use Authorize attribute:

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";
    }
}


来源:https://stackoverflow.com/questions/39192741/add-claims-to-windows-identity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!