如何将角色包括到JWT令牌返回中?

时间:2020-04-17 02:04:20

标签: asp.net-core angular8 asp.net-core-3.1

在浏览应用程序时,我的想法是,我想将令牌和角色名称一起保存到本地主机,然后检查用户是否可以访问特定链接。那是怎么回事?在Angular 8中使用Authgard?您能否给我一些有关如何使用Identity(从ASP.net core 3.1内置)中的角色导航应用程序的见解。

登录

  // POST api/auth/login
        [HttpPost("login")]
        public async Task<IActionResult> Post([FromBody]CredentialsViewModel credentials)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var identity = await GetClaimsIdentity(credentials.UserName, credentials.Password);
            if (identity == null)
            {
                //return null;
                return BadRequest(Error.AddErrorToModelState("login_failure", "Invalid username or password.", ModelState));
            }

            var jwt = await Tokens.GenerateJwt(identity, _jwtFactory, credentials.UserName, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented });
            return new OkObjectResult(jwt);
        }

生成令牌方法

       public static async Task<string> GenerateJwt(ClaimsIdentity identity, IJwtFactory jwtFactory, string userName, JwtIssuerOptions jwtOptions, JsonSerializerSettings serializerSettings)
            {
                var response = new
                {
                    id = identity.Claims.Single(c => c.Type == "id").Value,
                   //probably here I want to send the role too!!
                    auth_token = await jwtFactory.GenerateEncodedToken(userName, identity),
                    expires_in = (int)jwtOptions.ValidFor.TotalSeconds
                };

                return JsonConvert.SerializeObject(response, serializerSettings);
            }
        }


1 个答案:

答案 0 :(得分:0)

在生成JWT时,您需要添加声明信息。

这里是example

还有一个:

1 part(how to implement JWT)2 part(about claims here)