Esempio n. 1
0
        public IActionResult Refresh(RefreshTokenModel objRefreshTokenModel)
        {
            _logger.LogDebug(string.Format("refreshtoken method is called."));

            if (string.IsNullOrEmpty(objRefreshTokenModel.AccessToken) || string.IsNullOrWhiteSpace(objRefreshTokenModel.AccessToken) ||
                string.IsNullOrEmpty(objRefreshTokenModel.RefreshToken) || string.IsNullOrWhiteSpace(objRefreshTokenModel.RefreshToken) ||
                objRefreshTokenModel.LoginUserID == 0)
            {
                return(BadRequest(ResponseMessageModel.CreateResponseMessage("Token invalid.", "Access token and Refresh Token should not be empty.")));
            }

            var principal = objTokenHandler.GetPrincipalFromExpiredToken(objRefreshTokenModel.AccessToken);

            string identityName = principal.Identity.Name;

            if (string.IsNullOrEmpty(identityName) || string.IsNullOrWhiteSpace(identityName))
            {
                _logger.LogDebug(string.Format("Not able to identify user from JWT authentication mechanisam.Provided token is not valid."));
                return(BadRequest(ResponseMessageModel.CreateResponseMessage("Token invalid.", "Provided token is not valid.")));
            }

            long.TryParse(identityName, out long userID);
            if (Convert.ToInt64(userID) != 0 && (Convert.ToInt64(userID) != objRefreshTokenModel.LoginUserID))
            {
                _logger.LogDebug(string.Format("Provided token is not matched with logged in userID. LoginUserID:{0}", objRefreshTokenModel.LoginUserID, " and UserID generated from token is ", userID));
                return(BadRequest(ResponseMessageModel.CreateResponseMessage("Token invalid.", "Provided token is not matched with logged in userID.")));
            }

            _logger.LogDebug(string.Format("Generating new access token and refresh token for UserID:{0}", userID));
            // Get refresh token from db and check input refresh token is valid or not
            //var savedRefreshToken = GenerateRefreshToken(username); //retrieve the refresh token from a data store
            //if (savedRefreshToken != refreshToken)
            //    throw new SecurityTokenException("Invalid refresh token");

            var newJwtToken     = objTokenHandler.GenerateJWTToken(Convert.ToInt32(userID));
            var newRefreshToken = objTokenHandler.GenerateRefreshToken();

            //Save new refresh token into db
            //DeleteRefreshToken(username, refreshToken);
            //SaveRefreshToken(username, newRefreshToken);

            var res = new
            {
                accessToken  = newJwtToken,
                refreshToken = newRefreshToken
            };

            _logger.LogDebug(string.Format("Generated new access token and refresh token for UserID:{0}", userID));

            return(Ok(ResponseMessageModel.CreateResponseMessage(res, "Generated new access token and refresh token.")));
        }
Esempio n. 2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerManager logger)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            // intercept token expiration unauthorised request
            app.UseStatusCodePages(async context =>
            {
                if (context.HttpContext.Request.Path.StartsWithSegments("/api"))
                {
                    if (context.HttpContext.Response.StatusCode == 401 ||
                        context.HttpContext.Response.StatusCode == 403)
                    {
                        logger.LogError(string.Format("Unauthorized request. StatusCode:{0} Token is expired or is not valid.", context.HttpContext.Response.StatusCode));
                        await context.HttpContext.Response.WriteAsync(ResponseMessageModel.CreateResponseMessage("Unauthorised", "Token is expired or is not valid."));
                    }
                    else
                    {
                    }
                }
            });

            app.UseMiddleware <CustomExceptionMiddleware>();


            // AlLOW CORS request
            app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().WithExposedHeaders(new string[] { "Token-Expired" }));
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            // Register JWT authentication
            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        private async Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            var response        = context.Response;
            var customException = exception as BaseCustomException;
            var statusCode      = (int)HttpStatusCode.InternalServerError;
            var message         = "Unexpected error";
            var description     = exception.Message;

            if (null != customException)
            {
                message     = customException.Message;
                description = customException.Description;
                statusCode  = customException.Code;
            }

            response.ContentType = "application/json";
            response.StatusCode  = statusCode;
            await response.WriteAsync(ResponseMessageModel.CreateResponseMessage(message, description));
        }
Esempio n. 4
0
        public IActionResult Authenticate([FromBody] TokenRequestModel request)
        {
            _logger.LogDebug(string.Format("authenticate api called with parameters. Username:{0} ", request.Username));

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            UserModel objUser = _userService.IsValidUser(request.Username, request.Password);

            if (objUser == null)
            {
                _logger.LogDebug(string.Format("User is not valid. Username:{0} ", request.Username));
                return(BadRequest(ResponseMessageModel.CreateResponseMessage("Invalid User", "Username or password is not correct.")));
            }

            objUser.AccessToken  = objTokenHandler.GenerateJWTToken(objUser.UserID);
            objUser.RefreshToken = objTokenHandler.GenerateRefreshToken();

            _logger.LogDebug(string.Format("Generated access token and refresh token for UserID:{0}", objUser.UserID));

            return(Ok(objUser));
        }
Esempio n. 5
0
        public IActionResult GetAll()
        {
            List <UserModel> lstUser = _userService.GetUsers();

            return(Ok(ResponseMessageModel.CreateResponseMessage(lstUser, "All User list")));
        }