コード例 #1
0
        public IActionResult Login(LoginRequest loginRequest)
        {
            //TODO: check in db user credentials

            Student student = _studentsDbService.CheckIfInDb(loginRequest);

            // if ok create claims with it
            if (student == null)
            {
                return(Unauthorized("There is no such user in the dataBase, login or password are incorrect"));
            }


            var claims = new[] //TODO: those values must be from db
            {
                new Claim(ClaimTypes.NameIdentifier, student.IndexNumber.ToString()),
                new Claim(ClaimTypes.Name, student.FirstName),
                new Claim(ClaimTypes.Role, "student"),
                new Claim(ClaimTypes.Role, "employee")
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Secret_key"]));

            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken
                        (
                issuer: "TheRealMike",
                audience: "Everyone",
                claims: claims,
                expires: DateTime.Now.AddMinutes(10),
                signingCredentials: credentials

                        );

            Guid refreshToken = Guid.NewGuid();

            bool result = _studentsDbService.AddTokenToDb(refreshToken.ToString(), student.IndexNumber.ToString());

            if (!result)
            {
                throw new Exception();
            }

            return(Ok
                   (
                       new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token),
                refreshToken
            }
                   ));
        }