首页 > 解决方案 > Azure Active Directory Login Getting Claims 希望从本地数据库添加更多声明

问题描述

所以关于 SignIn 方法

  public IActionResult SignIn()
        {
           if (_unitOfWork.User.IsAuth(HttpContext) == true)
            {
                var _userCurrentObject = _unitOfWork.User.GetCurrentUserObject(HttpContext);
                var claims = new List<Claim>
            {
                new Claim("UserType",   _userCurrentObject.UserType),
           };
                var appIdentity = new ClaimsIdentity(claims);
                HttpContext.User.AddIdentity(appIdentity);
                User.AddIdentity(appIdentity);
                User.Claims.Append(new Claim("Wow", "value-x"));
                var zz = User;// i can see the Claim which i Add here but in other Action not able to see those Claims 
         
                return RedirectToAction("Index", "Home");
            }
            else
            {

                return RedirectToAction("AccessDenied", "Home");
            }


    }

像这样在其他控制器中访问这些声明

  string UserType = User.Claims.FirstOrDefault(c => c.Type == "UserType")?.Value;

到这里一切正常,但是当我应用程序尝试在其他操作中访问用户时,无法看到我添加的自定义声明,例如“Usertype”

我错过了什么吗?

标签: c#azure-active-directoryasp.net-core-mvc

解决方案


您可以使用 DI 以优雅的方式保存用户声明并使用它们IMemoryCache。代码如下:

启动.cs:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddTransient<IPrincipal>(
            provider => provider.GetService<IHttpContextAccessor>().HttpContext.User);
        services.AddTransient<IClaimsTransformation, ClaimsTransformer>();
        services.AddAuthentication(IISDefaults.AuthenticationScheme);

    }

ClaimsTransformer.cs:

using Microsoft.Extensions.Caching.Memory;

public class ClaimsTransformer : IClaimsTransformation
{
    private readonly IMemoryCache _cache;

    public ClaimsTransformer(IMemoryCache cache)
    {
        _cache = cache;
    }

    public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        var cacheKey = principal.FindFirstValue(ClaimTypes.NameIdentifier);

        if (_cache.TryGetValue(cacheKey, out List<Claim> claims)
        {
            ((ClaimsIdentity)principal.Identity).AddClaims(claims);
        }
        else
        {
            claims = new List<Claim>();          

            // call to database to get more claims based on user id ClaimsIdentity.Name

            _cache.Set(cacheKey, claims);
        }

        return principal;
    }
}

我还建议您阅读IMemoryCache此处:在 ASP.NET Core 中缓存内存


推荐阅读