Ejemplo n.º 1
0
        internal static KeyValuePair <JwtTokenValidationStatus, LoginResponseModel> Validate(string token)
        {
            if (!token.HasValue())
            {
                return(new KeyValuePair <JwtTokenValidationStatus, LoginResponseModel>(JwtTokenValidationStatus.NoToken, null));
            }

            try
            {
                string preSharedKey = Utilities.Utility.GetConfigValue("jwtTokenKey");
                using (HMACSHA256 hmac = new HMACSHA256(Encoding.ASCII.GetBytes(preSharedKey)))
                {
                    JwtSecurityTokenHandler tokenHandler   = new JwtSecurityTokenHandler();
                    SecurityToken           validatedToken = new JwtSecurityToken();
                    JwtSecurityToken        jwtToken       = tokenHandler.ReadJwtToken(token);

                    TokenValidationParameters validationParameters = new TokenValidationParameters
                    {
                        IssuerSigningKey = new SymmetricSecurityKey(hmac.Key),
                        ValidateAudience = false,
                        ValidateIssuer   = false
                    };

                    ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(token, validationParameters, out validatedToken);

                    if (jwtToken.ValidFrom < DateTime.UtcNow && jwtToken.ValidTo > DateTime.UtcNow)
                    {
                        string userId    = GetClaim(claimsPrincipal, Constants.CLAIM_USER_ID);
                        string sessionId = GetClaim(claimsPrincipal, Constants.CLAIM_SESSION_ID);

                        if (string.IsNullOrWhiteSpace(userId) || string.IsNullOrWhiteSpace(sessionId))
                        {
                            return(new KeyValuePair <JwtTokenValidationStatus, LoginResponseModel>(JwtTokenValidationStatus.Invalid, null));
                        }
                        LoginResponseModel loginModel = new LoginResponseModel
                        {
                            UserId    = userId,
                            SessionId = sessionId
                        };

                        return(new KeyValuePair <JwtTokenValidationStatus, LoginResponseModel>(JwtTokenValidationStatus.Valid, loginModel));
                    }
                    else
                    {
                        return(new KeyValuePair <JwtTokenValidationStatus, LoginResponseModel>(JwtTokenValidationStatus.Expired, null));
                    }
                }
            }
            catch (Exception ex)
            {
                LoggerService.LogException("", "JwtValidate", "ValidateJwtToken", ex);
                return(new KeyValuePair <JwtTokenValidationStatus, LoginResponseModel>(JwtTokenValidationStatus.Invalid, null));
            }
        }
Ejemplo n.º 2
0
        private User ValidateSession(AuthorizationFilterContext context, LoginResponseModel loginResponseModel)
        {
            User user = null;

            string sessionIdFromCache = CacheService.GetSessionId(context.HttpContext, loginResponseModel.SessionId);

            // TODO: Handle sessions between server restarts and app-updates
            if (!string.IsNullOrWhiteSpace(sessionIdFromCache))
            {
                user = CacheService.GetUserAsync(context.HttpContext, loginResponseModel.UserId).Result;
            }

            if (user == null)
            {
                using (TeamDbContext dbContext = new TeamDbContext())
                {
                    UserSession userSession = dbContext.UserSessions.FirstOrDefault(e => e.SessionId == loginResponseModel.SessionId && e.Active);

                    if (userSession == null)
                    {
                        context.Result = new UnauthorizedResult();
                        return(null);
                    }
                    user = dbContext.Users.FirstOrDefault(e => e.UserId == loginResponseModel.UserId.ToUpper(CultureInfo.InvariantCulture));

                    if (user == null)
                    {
                        context.Result = new UnauthorizedResult();
                        return(null);
                    }

                    //AuthService.PopulateUserClientsAsync(dbContext, user);

                    // save user to session
                    CacheService.StoreUserAsync(context.HttpContext, user);
                }
            }

            return(user);
        }
Ejemplo n.º 3
0
        public static async Task <ResponseBase <LoginResponseModel> > LoginAsync(TeamHttpContext teamHttpContext, LoginModel loginModel)
        {
            if (teamHttpContext == null)
            {
                throw new ArgumentNullException(nameof(teamHttpContext));
            }

            if (loginModel == null)
            {
                throw new ArgumentNullException(nameof(loginModel));
            }

            LoginResponseModel loginResponse = new LoginResponseModel
            {
                Status = LoginStatus.InValid
            };

            User user = new User();

            user = await ValidatePassword(teamHttpContext, loginModel).ConfigureAwait(false);

            if (user != null)
            {
                using (TeamDbContext dbContext = new TeamDbContext())
                {
                    if (user.UserId != null)
                    {
                        teamHttpContext.SetValue(Constants.CONTEXT_USER_ID, user.UserId);
                        loginResponse.Status = LoginStatus.LoggedIn;
                    }
                    else
                    {
                        loginResponse.Status = LoginStatus.NoAccess;
                    }

                    if (loginResponse.Status == LoginStatus.LoggedIn)
                    {
                        user.LastLoggedIn = DateTime.Now;
                        await dbContext.SaveChangesAsync().ConfigureAwait(false);
                    }
                }
            }

            if (loginResponse.Status == LoginStatus.LoggedIn)
            {
                string sessionId = Guid.NewGuid().ToString();
                await CreateSessionAsync(user.UserId, sessionId).ConfigureAwait(false);

                await CacheService.StoreSessionAsync(teamHttpContext, sessionId).ConfigureAwait(false);

                await CacheService.StoreUserAsync(teamHttpContext, user).ConfigureAwait(false);

                int  validity   = Utility.IsProduction ? 1 : 7;
                long validUntil = DateTime.UtcNow.AddDays(validity).GetUnixTimeStamp();
                loginResponse.Token           = Jwt.CreateToken(user, sessionId, validUntil);
                loginResponse.Email           = user.Email;
                loginResponse.UserId          = user.UserId;
                loginResponse.Type            = user.UserType;
                loginResponse.SessionId       = sessionId;
                loginResponse.ExpiryTimestamp = validUntil;
                loginResponse.IsAddRights     = user.IsAdd;
                loginResponse.IsEditRights    = user.IsEdit;
                loginResponse.IsDeleteRights  = user.IsDelete;

                return(GetTypedResponse <LoginResponseModel>(teamHttpContext, loginResponse));
            }
            else
            {
                return(GetUnauthorizedResponse <LoginResponseModel>(teamHttpContext, loginResponse));
            }
        }