首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >ASP.NET Core2.1JWT设置自定义声明

ASP.NET Core2.1JWT设置自定义声明
EN

Stack Overflow用户
提问于 2018-11-13 03:33:56
回答 1查看 1.2K关注 0票数 0

我有这样的代码,它应该为用户设置声明。当我使用标识和默认登录时,它可以正常工作。但是,当我在另一个应用程序中使用jwt作为身份验证时,我没有ApplicationUser,因为我的ApplicationUser存储在对用户进行身份验证的其他应用程序中。如何自定义此代码,使其与jwt协同工作?

代码语言:javascript
运行
复制
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 (服务器)

  • 负责对用户进行认证
  • 生成和解码Jwt
  • 检查用户是否具有适当的角色,并通过rest返回true/false。

MainApp (客户)

  • 对AuthenticationApp进行api调用
  • 根本不使用身份
  • 每次需要检查用户的角色时,都会发送Jwt。

我知道我将能够解码jwt客户端。但是,我不知道可以将解码的jwt细节存储在哪里,以便在视图中使用它。我最初的想法是像普通应用程序一样使用Httpcontext,即用户身份。但是,我被上面的代码卡住了。

EN

回答 1

Stack Overflow用户

发布于 2018-11-14 05:18:07

为了在Controller和View之间共享标识信息,可以使用HttpContext.SignInAsync对用户信息进行签名。

尝试下面的步骤来实现您的需求:

  • 控制器操作公共异步任务索引(){ var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme,ClaimTypes.Name,ClaimTypes.Role);identity.AddClaim(新索赔(ClaimTypes.NameIdentifier,"edward"));identity.AddClaim(新索赔(ClaimTypes.Name,"edward“));//从jwt令牌var主体=新ClaimsPrincipal(Identity)添加您自己的索赔;等待jwt主体,新AuthenticationProperties { IsPersistent = true };返回视图();}
  • 视图@foreach(Context.User.Claims中的var项){ @item.Value };
  • 若要使上述代码工作,请在Startup.cs中注册身份验证 公共类启动{公共启动( IConfiguration配置){配置=配置;}公共IConfiguration配置{ get;} //此方法将由运行时调用。使用此方法向容器添加服务。运行时调用公共ConfigureServices(IServiceCollection服务){ // rest代码IServiceCollection}//此方法。使用此方法配置HTTP请求管道。公共空配置(IApplicationBuilder app,IHostingEnvironment env) {//您的rest代码app.UseAuthentication();app.UseMvc(路由=> { routes.MapRoute(名称:“默认”,模板:"{controller=Home}/{action=Index}/{id?}");};}; }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53273404

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档