public async Task <IActionResult> Token([FromBody] LoginInput input)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var user = await _userRepository
                       .GetEntityAsync(x => x.UserName == input.UserName &&
                                       x.Password == EncryptHelper.AesEncrypt(_configuration["EncryptionKey"], input.Password));

            if (user == null)
            {
                return(BadRequest());
            }
            //这里可自定义申明信息,生成的token登录后可以获取到Claim信息
            var claim = new Claim[]
            {
                new Claim("id", user.Id),         //ClaimTypes.NameIdentifier
                new Claim("name", user.UserName), //ClaimTypes.Name
                new Claim("userNo", "0001"),      //todo-stwhh 需要根据自己需要修改
                //new Claim("role", "admin"), //
                //new Claim("email", "*****@*****.**")
            };

            //对称秘钥
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));
            //签名证书(秘钥,加密算法)
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            //生成token  [注意]需要nuget添加Microsoft.AspNetCore.Authentication.JwtBearer包,并引用System.IdentityModel.Tokens.Jwt命名空间
            var token = new JwtSecurityToken(
                issuer: _jwtSettings.Issuer,
                audience: _jwtSettings.Audience,
                claims: claim,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddMinutes(_jwtSettings.ExpiresInMinute), //有效期
                signingCredentials: creds);

            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();

            return(Ok(new { token = handler.WriteToken(token) }));
        }
        public async Task <GetUserOutput> GetUserById(GetUserInput input)
        {
            //var user = await _dbContext.User.Where(x => x.Id == input.UserId).FirstOrDefaultAsync();
            var user = await _userRepository.GetEntityAsync(x => x.Id == input.UserId);

            if (user == null)
            {
                return(null);
            }
            return(new GetUserOutput()
            {
                Id = user.Id,
                UserName = user.UserName,
                EnUserName = user.EnUserName,
                Password = user.Password,
                Email = user.Email,
                Phone = user.Phone
            });
        }
Exemple #3
0
 public async Task <IActionResult> GetUserAsync(string id) //[FromQuery] GetUserInput input
 {
     return(new JsonResult(await _userRepository.GetEntityAsync(x => x.Id == id)));
 }