向Windows身份添加声明 [英] add claims to windows identity

查看:71
本文介绍了向Windows身份添加声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

但是此方法未授权角色admin(403禁止访问).

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

如果使用[Authorize],它将正常工作.有什么遗漏吗?

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

推荐答案

不幸的是,User.IsInRole方法不适用于ClaimsTransformer(如果在ClaimsTransformer中添加角色,则IsInRole将为false),因此您不能使用[Authorize( Roles =")]与ClaimsTransformer.在这种情况下,您可以使用基于声明的授权来处理授权.

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.

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

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

这篇关于向Windows身份添加声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆