ASP.NET MVC 3 determines session status (new or timeout)

I am currently using the default forms authentication method for my ASP.NET MVC application.

first of all my action methods requiring authentication, I have this attribute

[Authorize()] 

When someone tries to call the page so that this action method "serves" and they are not logged in yet, he sends them to the login page ... great! However, if their session ends and they try to get to this page, they are also simply redirected to the login page without giving a reason. I would like to determine if this will be a new visit, or if it is a timeout and display another message on the login screen accordingly.

Is it possible?

+4
source share
2 answers

When you log in, you can set a cookie that is bound to a browser session. If this cookie exists, you know that the session has ended. If not, you know this is a new visit.

0
source

Take a look at this custom authorization attribute that I made. This should have done some role-based authorization, but you could have made it work for you too. There is a Session.IsNewSession property, which you can check to see if this request is being executed in a new session.

 public class CustomAuthorizeAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext.User.Identity.IsAuthenticated) { httpContext.User = new GenericPrincipal(httpContext.User.Identity, AdminUserViewModel.Current.SecurityGroups.Select(x => x.Name).ToArray()); } return base.AuthorizeCore(httpContext); } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (filterContext.HttpContext.User.Identity.IsAuthenticated) { filterContext.Result = new RedirectResult("/Authentication/NotAuthorized", false); } else { if (filterContext.HttpContext.Session.IsNewSession) { // Do Something For A New Session } base.HandleUnauthorizedRequest(filterContext); } } } 
+2
source

Source: https://habr.com/ru/post/1382379/


All Articles