2017-02-15 83 views
-2

如果會話過期,我想將用戶重定向到登錄頁面。我發現了很多方法來做到這一點,但什麼是與OWIN的ASP.Net MVC5最好(或默認)的方式? 也許它開箱即用?但是如何?會話過期後重定向到登錄頁面的最佳做法

剃刀:

  • 設置會話變量有效登錄後
  • 在_Layout.cshtml補充一點:
@if (Session["IsLogin"] == null) 
{ 
    Session.Abandon(); 
    Response.Redirect("~/LoginControllerName/LoginActionName"); 
} 

的Global.asax:

  • 這是可能使用這兩種方法,但我不知道如何。
protected void Session_Start(object sender, EventArgs e) 
{ 
    // Code that runs when a new session is started 
} 

protected void Session_End(object sender, EventArgs e) 
{ 
    // Code that runs when a session is expired 
} 

我目前的解決方案:

  • 所有的控制器繼承BaseController
  • 我用OnAuthorizationAttribute因爲重定向如果它是一個非公開的頁面應該只執行。
public abstract class BaseController : Controller 
{ 
    protected override void OnAuthorization(AuthorizationContext filterContext) 
    { 
     if (this.Session["RedirectAfterLogin"] == null) 
     { 
      var isAnonymousAllowed = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true); 
      if (!isAnonymousAllowed) 
      { 
       this.Session["RedirectAfterLogin"] = this.Request.Url?.ToString(); 
       filterContext.Result = this.RedirectToAction("LoginActionName", "LoginControllerName"); 
      } 
     } 
     base.OnAuthorization(filterContext); 
    } 
} 
  • 後重定向註銷用戶:
if (this.AuthenticationManager == null) 
{ 
    this.SetAuthenticationManager(this.HttpContext?.GetOwinContext()?.Authentication); 
} 

this.AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); 
  • 有效的登錄設置會話變量之後:
this.Session["RedirectAfterLogin"] = this.Request.Url?.ToString(); 

回答

0

一個一個像一個定製CookieAuthenticationProvider處理當前頁面即可額外信息會話過期後重定向。

public partial class Startup 
{ 
    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 
    public void ConfigureAuth(IAppBuilder app) 
    { 
     // Configure the db context, user manager and signin manager to use a single instance per request 
     app.CreatePerOwinContext(ApplicationDbContext.Create); 
     app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); 
     app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create); 

     var url = new UrlHelper(HttpContext.Current.Request.RequestContext); 
     var provider = new CookieAuthenticationProvider(); 
     var originalHandler = provider.OnApplyRedirect; 
     provider.OnApplyRedirect = context => 
     { 
      var routeValues = new RouteValueDictionary(); 
      var uri = new Uri(context.RedirectUri); 
      var returnUrl = HttpUtility.ParseQueryString(uri.Query)[context.Options.ReturnUrlParameter]; 
      routeValues.Add(context.Options.ReturnUrlParameter, returnUrl); 
      context.RedirectUri = url.Action("Login", "Account", routeValues); 
      originalHandler.Invoke(context); 
     }; 
     provider.OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
        validateInterval: TimeSpan.FromMinutes(30), 
        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)); 


     app.UseCookieAuthentication(new CookieAuthenticationOptions 
     { 
      AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, 
      LoginPath = new PathString("/Account/Login"), 
      Provider = provider, 
      SlidingExpiration = true, 
      ExpireTimeSpan = TimeSpan.FromMinutes(30) 
     });    
     app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); 

     // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process. 
     app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); 
     app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); 
    } 
} 
0

你在mvc5使用的默認啓動owin

public partial class Startup 
{ 
    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 
    public void ConfigureAuth(IAppBuilder app) 
    { 
     // Configure the db context, user manager and signin manager to use a single instance per request 
     app.CreatePerOwinContext(ApplicationDbContext.Create); 
     app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); 
     app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create); 
     app.UseCookieAuthentication(new CookieAuthenticationOptions 
     { 
      AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, 
      LoginPath = new PathString("/Account/Login"), 
      Provider = new CookieAuthenticationProvider 
      { 

       OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
        validateInterval: TimeSpan.FromMinutes(30), 
        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) 
      } 
     });    
     app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); 

     // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process. 
     app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); 

     app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); 

    } 
} 
+0

這看起來像我的配置。我另外設置了'''SlidingExpiration = true''和 '''ExpireTimeSpan = TimeSpan.FromMinutes(30)'''。但在我的web.config中,我有一個不同的會話超時'''''' – cSteusloff

相關問題