Example #1
0
        // AuthenticationFailed, try again using the refreshToken
        public override async Task AuthenticationFailed(AuthenticationFailedContext context)
        {
            try {
                GetTokensFromRequestContext(context.HttpContext.Request, out string token, out string refreshToken);
                if (!string.IsNullOrEmpty(token) && !string.IsNullOrEmpty(refreshToken))
                {
                    // validate refreshToken in DB
                    var refreshTokenSearch = await tokensRepository.Get(t => t.Token == refreshToken);

                    if (refreshTokenSearch == null || refreshTokenSearch.Count == 0)
                    {
                        WriteExceptionToHttpResponse(context.HttpContext.Response, ErrorStatusCode.RefreshTokenExpired);
                        throw ErrorStatusCode.RefreshTokenExpired;
                    }
                    var(claims, jwtUser) = jwtManager.ReadToken(token, false);
                    var newToken = jwtManager.GenerateToken(jwtUser);
                    // Delete previous token from database
                    await tokensRepository.DeleteById(refreshTokenSearch[0].Id);

                    // Create a new token in Database
                    await tokensRepository.Post(new UserToken {
                        UserId      = newToken.UserId,
                        Token       = newToken.RefreshToken,
                        TokenTypeId = (long)Data.Enums.TokenType.RefreshToken,
                        ExpiryTime  = DateTime.Now.AddSeconds(jwtManager.RefreshTokenTTLSeconds)
                    });

                    context.Principal = claims;
                    // if there was a cookie, then set again the cookie with the new value
                    if (!string.IsNullOrEmpty(context.HttpContext.Request.Cookies[AppConstants.SessionCookie]))
                    {
                        context.HttpContext.SetCookie(AppConstants.SessionCookie, Newtonsoft.Json.JsonConvert.SerializeObject(new Dictionary <string, string> {
                            [AppConstants.Token]        = newToken.Token,
                            [AppConstants.RefreshToken] = newToken.RefreshToken
                        }));
                    }
                    // If everything goes ok set request principal (In this point authentication is done and ok)
                    context.Success();
                }
            }
            catch {
                return;
            }
            return;
        }