public async Task <IActionResult> Login([FromBody] UserLoginDTO loginUser)
        {
            if (loginUser == null)
            {
                return(BadRequest("User is not set."));
            }

            Models.DbModels.User user = await _usersService.FindUserPasswordAsync(loginUser.Username, loginUser.Password);

            if (user == null || !user.Enabled)
            {
                return(Unauthorized("InvalidCredentials"));
            }

            if (!user.IsApproved)
            {
                return(Unauthorized("NotApproved"));
            }

            (string accessToken, string refreshToken, System.Collections.Generic.IEnumerable <Claim> claims) = await _tokenStoreService.CreateJwtTokens(user, refreshTokenSource : null);

            return(Ok(new AccessToken {
                access_token = accessToken, refresh_token = refreshToken
            }));
        }
Пример #2
0
        public async Task ValidateAsync(TokenValidatedContext context)
        {
            ClaimsPrincipal userPrincipal = context.Principal;

            ClaimsIdentity claimsIdentity = context.Principal.Identity as ClaimsIdentity;

            if (claimsIdentity?.Claims == null || !claimsIdentity.Claims.Any())
            {
                context.Fail("This is not our issued token. It has no claims.");
                return;
            }

            Claim serialNumberClaim = claimsIdentity.FindFirst(ClaimTypes.SerialNumber);

            if (serialNumberClaim == null)
            {
                context.Fail("This is not our issued token. It has no serial.");
                return;
            }

            string userIdString = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier).Value;

            if (!int.TryParse(userIdString, out int userId))
            {
                context.Fail("This is not our issued token. It has no user-id.");
                return;
            }

            Models.DbModels.User user = await _usersService.FindUserAsync(userId);

            if (user == null || user.SerialNumber != serialNumberClaim.Value || !user.Enabled)
            {
                // user has changed his/her password/roles/stat/IsActive
                context.Fail("This token is expired. Please login again.");
            }

            JwtSecurityToken accessToken = context.SecurityToken as JwtSecurityToken;

            if (accessToken == null || string.IsNullOrWhiteSpace(accessToken.RawData) ||
                !await _tokenStoreService.IsValidTokenAsync(accessToken.RawData, userId))
            {
                context.Fail("This token is not in our database.");
                return;
            }

            await _usersService.UpdateUserLastActivityDateAsync(userId);
        }