Exemple #1
0
        public async Task Validate(string sourceClass, string sourceMethod)
        {
            // Check if JWT token exists in session, if not redirect to login page
            if (string.IsNullOrEmpty(_httpContextAccessor.HttpContext.Session.GetString("_JwtToken")))
            {
                throw new TokenException("You are not logged in", sourceClass, sourceMethod, "401");
            }

            // JWT exist in session, check if expired
            if (Convert.ToDateTime(_httpContextAccessor.HttpContext.Session.GetString("_JwtExpiresOn")) < DateTime.UtcNow)
            {
                // Unnecesary because check is done at back-end but this client-side check saves an API call
                // Check if refresh token is expired
                // If expired the user needs to authenticate with credentials
                if (Convert.ToDateTime(_httpContextAccessor.HttpContext.Session.GetString("_RtExpiresOn")) < DateTime.UtcNow)
                {
                    throw new TokenException("Your session has expired", sourceClass, sourceMethod, "401");
                }

                // If not expired a request to /api/Users/refresh-token is required to get a new set of tokens
                PostAuthenticateResponseModel postAuthenticateResponseModel = await _moviemindAPIService.RefreshToken();

                // Update the session data with the new set of tokens
                _stateManagementService.SetState(postAuthenticateResponseModel);
            }
        }
Exemple #2
0
        public async Task <PostAuthenticateResponseModel> Authenticate(PostAuthenticateRequestModel postAuthenticateRequestModel)
        {
            var postAuthenticateRequestModelJson = new StringContent(
                JsonSerializer.Serialize(postAuthenticateRequestModel),
                Encoding.UTF8,
                "application/json");

            using var httpResponse = await _httpClient.PostAsync("users/authenticate", postAuthenticateRequestModelJson);

            using var httpResponseStream = await httpResponse.Content.ReadAsStreamAsync();

            if (httpResponse.IsSuccessStatusCode)
            {
                // Get the Refresh Token details out of the response and save them in the model
                string refreshToken = httpResponse.Headers.GetValues("Set-Cookie").SingleOrDefault();

                PostAuthenticateResponseModel postAuthenticateResponseModel = await JsonSerializer.DeserializeAsync <PostAuthenticateResponseModel>(httpResponseStream);

                postAuthenticateResponseModel.RefreshToken = refreshToken;

                return(postAuthenticateResponseModel);
            }

            throw await JsonSerializer.DeserializeAsync <MovieMindException>(httpResponseStream);
        }
Exemple #3
0
        public async Task <ActionResult <PostAuthenticateResponseModel> > Authenticate(PostAuthenticateRequestModel postAuthenticateRequestModel)
        {
            try
            {
                PostAuthenticateResponseModel postAuthenticateResponseModel = await _userRepository.Authenticate(postAuthenticateRequestModel, IpAddress());

                SetTokenCookie(postAuthenticateResponseModel.RefreshToken);

                return(postAuthenticateResponseModel);
            }
            catch (MovieMindException e)
            {
                return(Unauthorized(e.MovieMindError));
            }
        }
        [ValidateAntiForgeryToken] // Prevents XSRF/CSRF attacks
        public async Task <IActionResult> Index(PostUserModel postUserModel, string rememberMe)
        {
            if (postUserModel.Password != postUserModel.ConfirmPassword)
            {
                ModelState.AddModelError("ConfirmPassword", _localizer["Passwords are not the same"]);
            }

            if (ModelState.IsValid)
            {
                try
                {
                    if (postUserModel.Roles == null)
                    {
                        postUserModel.Roles = new List <String>
                        {
                            "Guest"
                        };
                    }
                    else if (postUserModel.Roles.Count == 0)
                    {
                        postUserModel.Roles.Add("Guest");
                    }
                    // Send an API request to create the new user
                    GetUserModel getUserModel = await _moviemindAPIService.PostModel <PostUserModel, GetUserModel>(postUserModel, "users");

                    // When the user was successfully created send an API request to authenticate the new user
                    PostAuthenticateRequestModel postAuthenticateRequestModel = new PostAuthenticateRequestModel
                    {
                        UserName = postUserModel.UserName,
                        Password = postUserModel.Password,
                    };

                    PostAuthenticateResponseModel postAuthenticateResponseModel = await _moviemindAPIService.Authenticate(postAuthenticateRequestModel);

                    _stateManagementService.SetState(postAuthenticateResponseModel);

                    // Redirect to the home page
                    return(RedirectToRoute(new { action = "Index", controller = "Home" }));
                }
                catch (MovieMindException e)
                {
                    TempData["ApiError"] = e.Message;
                }
            }

            return(View(postUserModel));
        }
Exemple #5
0
        public async Task <ActionResult <PostAuthenticateResponseModel> > RefreshToken()
        {
            try
            {
                string refreshToken = Request.Cookies["MovieMind.RefreshToken"];

                PostAuthenticateResponseModel postAuthenticateResponseModel = await _userRepository.RefreshToken(refreshToken, IpAddress());

                SetTokenCookie(postAuthenticateResponseModel.RefreshToken);

                return(postAuthenticateResponseModel);
            }
            catch (MovieMindException e)
            {
                return(Unauthorized(e.MovieMindError));
            }
        }
        public async Task InvokeAsync(HttpContext context, MoviemindAPIService movieMindAPIService, IStateManagementService stateManagementService)
        {
            // Token validation is not required for authentication and registration
            if (!context.Request.Path.Value.Contains("Registration") && !context.Request.Path.Value.Contains("Authentication"))
            {
                // Check if JWT token exists in session, if not redirect to login page
                if (string.IsNullOrEmpty(context.Session.GetString("_JwtToken")))
                {
                    context.Response.Redirect("/Authentication");
                    return;
                }
                else
                {
                    var expiresOn = Convert.ToDateTime(context.Session.GetString("_JwtExpiresOn"));
                    // JWT exist in session, check if expired
                    if (expiresOn < DateTime.UtcNow)
                    {
                        // Unnecesary because check is done at back-end but this client-side check saves an API call
                        // Check if refresh token is expired
                        // If expired the user needs to authenticate with credentials
                        var rtexpireson = Convert.ToDateTime(context.Session.GetString("_RtExpiresOn"));
                        if (rtexpireson < DateTime.UtcNow)
                        {
                            context.Session.SetString("SessionExpired", "Your session is expired");
                            context.Response.Redirect("/Authentication");
                            return;

                            //throw new TokenException("Uw sessie is verlopen", "TokenValidationMiddleware", "InvokeAsync", "401");
                        }
                        else
                        {
                            // If not expired a request to /api/Users/refresh-token is required to get a new set of tokens
                            PostAuthenticateResponseModel postAuthenticateResponseModel = await movieMindAPIService.RefreshToken();

                            // Update the session data with the new set of tokens
                            stateManagementService.SetState(postAuthenticateResponseModel);
                        }
                    }
                }
            }

            // Call the next delegate/middleware in the pipeline
            await _next(context);
        }
Exemple #7
0
        public async Task <PostAuthenticateResponseModel> RefreshToken()
        {
            using var httpResponse = await _httpClient.PostAsync("users/refresh-token", null);

            using var httpResponseStream = await httpResponse.Content.ReadAsStreamAsync();

            if (httpResponse.IsSuccessStatusCode)
            {
                // Get the Refresh Token details out of the response and save them in the model
                string refreshToken = httpResponse.Headers.GetValues("Set-Cookie").SingleOrDefault();

                PostAuthenticateResponseModel postAuthenticateResponseModel = await JsonSerializer.DeserializeAsync <PostAuthenticateResponseModel>(httpResponseStream);

                postAuthenticateResponseModel.RefreshToken = refreshToken;

                return(postAuthenticateResponseModel);
            }

            throw await JsonSerializer.DeserializeAsync <MovieMindException>(httpResponseStream);
        }
        public void SetState(PostAuthenticateResponseModel postAuthenticateResponseModel)
        {
            string refreshToken = postAuthenticateResponseModel.RefreshToken.Split(';').Single(x => x.Contains("MovieMind.RefreshToken=")).Substring(24);
            string rtExpiresOn  = postAuthenticateResponseModel.RefreshToken.Split(';').Single(x => x.Contains("expires=")).Substring(9);

            StateManagementModel stateManagementModel = new StateManagementModel
            {
                Id           = postAuthenticateResponseModel.Id,
                FirstName    = postAuthenticateResponseModel.FirstName,
                LastName     = postAuthenticateResponseModel.LastName,
                UserName     = postAuthenticateResponseModel.UserName,
                JwtToken     = postAuthenticateResponseModel.JwtToken,
                JwtExpiresOn = handler.ReadJwtToken(postAuthenticateResponseModel.JwtToken).ValidTo,
                RefreshToken = refreshToken,
                RtExpiresOn  = Convert.ToDateTime(rtExpiresOn).ToUniversalTime(),
                Roles        = postAuthenticateResponseModel.Roles
            };

            SetSessionData(stateManagementModel);
        }
Exemple #9
0
        [ValidateAntiForgeryToken] // Prevents XSRF/CSRF attacks
        public async Task <IActionResult> Index(PostAuthenticateRequestModel postAuthenticateRequestModel)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    // Send an API request to authenticate the new user
                    PostAuthenticateResponseModel postAuthenticateResponseModel = await _moviemindAPIService.Authenticate(postAuthenticateRequestModel);

                    _stateManagementService.SetState(postAuthenticateResponseModel);

                    // Redirect to the home page
                    return(RedirectToRoute(new { action = "Index", controller = "Home" }));
                }
                catch (MovieMindException e)
                {
                    TempData["ApiError"] = e.Message;
                }
            }

            return(View(postAuthenticateRequestModel));
        }