예제 #1
0
        public IActionResult Refresh(TokenApiModel tokenApiModel)
        {
            if (tokenApiModel is null)
            {
                return(BadRequest("Invalid client request"));
            }

            string accessToken  = tokenApiModel.AccessToken;
            string refreshToken = tokenApiModel.RefreshToken;

            var principal = tokenService.GetPrincipalFromExpiredToken(accessToken);
            var username  = principal.Identity.Name; //this is mapped to the Name claim by default

            var user = sirhContext.User.SingleOrDefault(u => u.Email == username);

            if (user == null || user.RefreshToken != refreshToken || user.RefreshTokenExpiryTime <= DateTime.Now)
            {
                return(BadRequest("Invalid client request"));
            }

            var newAccessToken  = tokenService.GenerateAccessToken(principal.Claims);
            var newRefreshToken = tokenService.GenerateRefreshToken();

            user.RefreshToken = newRefreshToken;
            sirhContext.SaveChanges();

            return(new ObjectResult(new
            {
                accessToken = newAccessToken,
                refreshToken = newRefreshToken
            }));
        }
예제 #2
0
        public IActionResult Login([FromBody] User loginModel)
        {
            if (loginModel == null)
            {
                return(BadRequest("Invalid client request"));
            }
            var user = sirhContext.User
                       .FirstOrDefault(u => (u.Email == loginModel.Email) &&
                                       (u.Password == loginModel.Password));

            if (user == null)
            {
                return(Unauthorized());
            }
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, loginModel.Email),
            };
            var accessToken  = tokenService.GenerateAccessToken(claims);
            var refreshToken = tokenService.GenerateRefreshToken();

            user.RefreshToken           = refreshToken;
            user.RefreshTokenExpiryTime = DateTime.Now.AddDays(7);
            sirhContext.SaveChanges();
            return(Ok(user));
        }