2017-02-15 9 views
-2

セッションが終了すると、ユーザーをログインページにリダイレクトします。私はこれを行うための多くの方法を見つけましたが、ASP.Net MVC5とOWINのベストな(またはデフォルトの)方法は何ですか? おそらくそれは箱の外で動作しますか?しかし、どのように?セッションの有効期限が切れた場合にログインページにリダイレクトするためのベストプラクティス

レイザー:

  • は有効なログイン
  • 後にセッション変数を設定_Layout.cshtmlでこれを追加:
@if (Session["IsLogin"] == null) 
{ 
    Session.Abandon(); 
    Response.Redirect("~/LoginControllerName/LoginActionName"); 
} 

のGlobal.asax:

  • ことがありますこれらの2つの方法を使用することは可能ですが、私は方法がわかりません。
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 
} 

私の現在のソリューション:

  • すべてのコントローラにリダイレクトので、私はOnAuthorizationAttributeを使用BaseController
  • から継承し、それは非公開ページである場合にのみ実行されなければなりません。
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

Aカスタム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

関連する問題