How to add Roles to Windows Authentication in ASP.NET Core

前端 未结 3 1985
梦谈多话
梦谈多话 2021-01-31 06:40

I created an asp.net core project in visual studio 2015 with windows authentication. I can\'t figure out how to add roles to the Identity.

I have a table with usernames

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-31 06:59

    With Windows Authentication the roles come from Active Directory, not a database.

    You could use Claims Transformation to change the inbound identity on every request to pull extra roles from your database.

    public class ClaimsTransformer : IClaimsTransformer
    {
        public Task TransformAsync(ClaimsPrincipal principal)
        {
            ((ClaimsIdentity)principal.Identity).AddClaim(
                new Claim("ExampleClaim", "true"));
            return Task.FromResult(principal);
        }
    }
    

    And then wire it up with

    app.UseClaimsTransformation(new ClaimsTransformationOptions
    {
        Transformer = new ClaimsTransformer()
    });
    

    Note that in the current incarnation there's no DI support, so you'll have to manually pull out your database information from DI if that's where it is.

提交回复
热议问题