如何更新 ASP.NET Core 中的声明

Fai*_*eem 3 asp.net-core asp.net-core-identity

我使用以下代码添加了声明

var claims = new List<Claim>
                 {
                    new Claim(Constants.ClaimTypes.BUSINESS_ID, user.BusinessID.ToString()),
                    new Claim(Constants.ClaimTypes.NAME, user.FullName),
                    new Claim(Constants.ClaimTypes.IMAGE, user.ProfileUrl ?? user.LogoUrlEn ?? user.LogoUrlEn ?? ""),
                    new Claim(Constants.ClaimTypes.EMAIL, user.Email),
                    new Claim(Constants.ClaimTypes.USER_ID, user.UserID.ToString()),
                    new Claim(Constants.ClaimTypes.ROLE, user.RoleID.ToString()),
                    new Claim(Constants.ClaimTypes.RIGHTS, string.Join(',', user.RolesRights.Select(S => $"{S.EntityName}|{S.EntityID}|{S.RightID}")))
                };

var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

var authProperties = new AuthenticationProperties
        {
            AllowRefresh = true,
            IsPersistent = true,
            RedirectUri = "/Authentication/Login"
        };

await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                              new ClaimsPrincipal(claimsIdentity),
                              authProperties);
Run Code Online (Sandbox Code Playgroud)

当有人更新个人资料图片时,我需要更新声明,我需要更新它,我该怎么做?

我尝试了几种解决方案,但没有任何效果。

当有人更新个人资料图片时,必须注销并再次登录才能看到效果。

Bra*_*ang 6

如您所知,登录时声明将存储在 cookie 中。

因此,如果您想更新声明,则需要使用更新后的声明重新调用登录用户代码。

与之前添加声明代码一样:

var claims = new List<Claim>
                 {
                    new Claim(Constants.ClaimTypes.BUSINESS_ID, user.BusinessID.ToString()),
                    new Claim(Constants.ClaimTypes.NAME, user.FullName),
                    new Claim(Constants.ClaimTypes.IMAGE, user.ProfileUrl ?? user.LogoUrlEn ?? user.LogoUrlEn ?? ""),
                    new Claim(Constants.ClaimTypes.EMAIL, user.Email),
                    new Claim(Constants.ClaimTypes.USER_ID, user.UserID.ToString()),
                    new Claim(Constants.ClaimTypes.ROLE, user.RoleID.ToString()),
                    new Claim(Constants.ClaimTypes.RIGHTS, string.Join(',', user.RolesRights.Select(S => $"{S.EntityName}|{S.EntityID}|{S.RightID}")))
                };

var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

var authProperties = new AuthenticationProperties
        {
            AllowRefresh = true,
            IsPersistent = true,
            RedirectUri = "/Authentication/Login"
        };

await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                              new ClaimsPrincipal(claimsIdentity),
                              authProperties);
Run Code Online (Sandbox Code Playgroud)

  • 是的,没办法。声明存储在客户端的 cookie 中。如果您想更新,则需要再次更新 cookie。 (2认同)