使用Windows身份验证时向身份添加自定义声明 [英] Add custom claims to identity when using Windows authentication

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

问题描述

在.Net MVC应用程序中使用Windows身份验证时,我很难理解如何添加自定义声明.

I am having a difficult time understanding how to add custom claims when using Windows authentication in a .Net MVC app.

这里的挑战是用登录时数据库中的自定义声明填充用户的身份,以避免每次我要检查自定义授权属性时都进行数据库调用.但是Windows身份验证的使用使我的事情变得复杂,因为没有登录方法可以放置用于填充角色的代码.

The challenge here is to populate the users's identity with custom claims from the database on login, so as to avoid making a db call every time I want to check a custom authorization attribute. But the use of Windows auth complicates things for me, as there's no login method in which to put the code that populates the roles.

是否有一种方法可以替代Windows身份验证登录过程?

Is there a method to override, or some other way to hook into the Windows auth login process?

推荐答案

.NET Core 2.0 中,您应该使用IClaimsTransformation.

In .NET Core 2.0 you should use IClaimsTransformation.

例如:

public class CustomClaimsTransformer : IClaimsTransformation
{
    public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        ((ClaimsIdentity)principal.Identity)
          .AddClaim(new Claim(claim.Name, claim.Value)); //your values

        return Task.FromResult(principal);
    }
}

并将此代码添加到Startup.cs

And add this code to Startup.cs

...
services.AddMvc();

services.AddScoped<IClaimsTransformation,CustomClaimsTransformer>(); // Add this

我不知道如何在ASP.NET MVC中执行此操作.

I don't know how to do this in ASP.NET MVC :/.

这是我在这里的第一个答案:).

This is my first answer here :).

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

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