Exemplo n.º 1
0
        public async Task <IActionResult> CreateJwt(string userEmail, string password)
        {
            try
            {
                var result = await _userServer.ReturnCheckEmailAndPasswordAsync(userEmail, password);

                if (result == null)
                {
                    return(Unauthorized());
                }
                var claims = new[]
                {
                    new Claim(ClaimTypes.Name, result.UserName),
                    new Claim(JwtRegisteredClaimNames.Email, result.Email),
                    new Claim(ClaimTypes.NameIdentifier, result.Id.ToString()),
                };

                var key   = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(_config.JwtSecurityKey)); //授权密匙
                var token = new JwtSecurityToken(
                    issuer: _config.Issuer,                                                                       //授权签发者
                    audience: _config.Audience,                                                                   //授权签收者
                    claims: claims,
                    expires: DateTime.Now.AddMinutes(5),                                                          //过期时间
                    signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));

                //生成Token
                string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
                return(Ok(new
                {
                    access_token = jwtToken,
                    token_type = "Bearer",
                }));
            }
            catch (Exception ex)
            {
                _logger.LogError("获取访问令牌时发生错误!", ex);
                return(Json(new { Error = "授权失败", Code = 401 }));
            }
        }