[英]ASP.NET Core 2.1 Jwt setting custom claims
我有应该为用户设置声明的这段代码。 当我使用身份和默认登录名时,它工作正常。 但是,当我在另一个应用程序中将jwt用作身份验证时,我没有ApplicationUser,因为我的ApplicationUser存储在对用户进行身份验证的另一个应用程序中。 如何自定义此代码,使其与jwt一起使用?
private readonly SignInManager<TIdentityUser> _signInManager;
public CustomClaimsCookieSignInHelper(SignInManager<TIdentityUser> signInManager)
{
_signInManager = signInManager;
}
public async Task SignInUserAsync(TIdentityUser user, bool isPersistent, IEnumerable<Claim> customClaims)
{
var claimsPrincipal = await _signInManager.CreateUserPrincipalAsync(user);
var identity = claimsPrincipal.Identity as ClaimsIdentity;
var claims = (from c in claimsPrincipal.Claims select c).ToList();
var savedClaims = claims;
if (customClaims != null)
{
identity.AddClaims(customClaims);
}
await _signInManager.Context.SignInAsync(IdentityConstants.ApplicationScheme,
claimsPrincipal,
new AuthenticationProperties { IsPersistent = isPersistent });
}
我想我的主要目的是在httpcontext中而不是在cookie中设置我的用户声明,而我想这样做而不使用身份。
编辑:
我的应用程序结构
AuthenticationApp(服务器)
MainApp(客户端)
我知道我将能够解码jwt客户端。 但是,我不知道在哪里可以存储已解码的jwt详细信息,以便可以在视图中使用它。 我最初的想法是像使用用户身份的普通应用程序一样使用Httpcontext。 但是,我坚持上面的代码。
为了在Controller和View之间共享身份信息,可以通过HttpContext.SignInAsync
签名用户信息。
请尝试以下步骤来满足您的要求:
控制器动作
public async Task<IActionResult> Index() { var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "edward")); identity.AddClaim(new Claim(ClaimTypes.Name, "edward zhou")); //add your own claims from jwt token var principal = new ClaimsPrincipal(identity); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true }); return View(); }
视图
@foreach (var item in Context.User.Claims) { <p>@item.Value</p> };
要使上述代码起作用,请在Startup.cs
注册身份验证
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //your rest code services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { //your rest code app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.