我有应该为用户设置声明的这段代码。当我使用身份和默认登录名时,它工作正常。但是,当我在另一个应用程序中将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。但是,我坚持上面的代码。
答案 0 :(得分:0)
要在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?}");
});
}
}