コード例 #1
0
        public async Task <IActionResult> Token([FromBody] CreateNewTokenDto model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState.Values.SelectMany(v => v.Errors).Select(modelError => modelError.ErrorMessage).ToList()));
                }

                var userEntity = _mapper.Map <UserEntity>(model);

                return(await _authService.CreateToken(model));
            }
            catch (AppException ex) { return(BadRequest(new { message = ex.Message })); }
        }
コード例 #2
0
        public async Task <IActionResult> CreateToken(CreateNewTokenDto model)
        {
            var user = await _userManager.FindByNameAsync(model.UserName);

            if (user == null || _passwordHasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) != PasswordVerificationResult.Success)
            {
                throw new AppException("Wrong user or password!");
            }

            // generate token
            var token = await GetJwtSecurityToken(user);

            // Checks the old refreshToken exists is valid and exists
            if (!_context.RefreshTokens.Any(x => x.Username == model.UserName && x.Revoked == false && x.Token == model.RefreshToken))
            {
                throw new AppException("Wrong parameters!");    // error 400
            }
            // generate token refresh token
            RefreshTokens NewRefreshToken = GenerateRefreshToken(user);

            //Update refreshToken
            RefreshTokens oldRefreshToken = _context.RefreshTokens.Single(x => x.Username == model.UserName && x.Revoked == false && x.Token == model.RefreshToken);

            if (oldRefreshToken == null)
            {
                throw new AppException("Wrong parameters oldRefreshToken!"); // error 400
            }
            var resultRemove = _context.RefreshTokens.Remove(oldRefreshToken);
            var resultAdd    = _context.RefreshTokens.AddAsync(NewRefreshToken);
            await _context.SaveChangesAsync();

            return(Ok(new
            {
                access_token = new JwtSecurityTokenHandler().WriteToken(token),
                expires_in = token.ValidTo,
                refresh_token = NewRefreshToken.Token
            }));
        }