会话过期时重定向到登录页面的最佳做法

时间:2017-02-15 08:40:29

标签: c# asp.net-mvc session asp.net-mvc-5 owin

如果会话已过期,我想将用户重定向到登录页面。我发现有很多方法可以做到这一点,但是ASP.Net MVC5中使用OWIN的最佳(或默认)方式是什么? 可能它开箱即用?但是怎么样?

剃刀:

  • 在有效登录后设置会话变量
  • 在_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();

2 个答案:

答案 0 :(得分:1)

过期会话后的重定向以及当前页面等其他信息可以使用自定义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);
    }
}

答案 1 :(得分: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);

    }
}