示例#1
0
        public IActionResult Login(LoginDto request)
        {
            User user = _dbService.GetUserCredentials(request.Username);

            if (user != null)
            {
                var userValidated = _dbService.Validate(request.Password, user.Salt, user.HashedPassword);
                if (userValidated)
                {
                    var claims = new[]
                    {
                        new Claim(ClaimTypes.Name, user.Username),
                        new Claim(ClaimTypes.Role, user.Role),
                    };

                    var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecretKey"]));
                    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                    var token = new JwtSecurityToken
                                (
                        issuer: "Gakko",
                        audience: "Students",
                        claims: claims,
                        expires: DateTime.Now.AddMinutes(10),
                        signingCredentials: creds
                                );

                    return(Ok(new
                    {
                        accessToken = new JwtSecurityTokenHandler().WriteToken(token),
                        refreshToken = Guid.NewGuid()
                    }));
                }
                else
                {
                    return(BadRequest());
                }
            }
            else
            {
                return(BadRequest());
            }
        }