身份会话开始

时间:2014-12-15 11:19:41

标签: .net session cookies asp.net-identity

在MVC 5项目中,我使用的是Microsoft.AspNet.Identity。我希望授权用户使用cookie和会话。我在redis上录制会话。

 <sessionState mode="Custom" customProvider="MySessionStateStore">
  <providers>
      <add name="MySessionStateStore" 
           type="Microsoft.Web.Redis.RedisSessionStateProvider"
        host="192.168.13.197"
        port = "6379" 
        accessKey = "" 
        ssl = "false"
        throwOnError = "true"
        retryTimeoutInMilliseconds = "5000" 
        databaseId = "0" 
        applicationName = "IddaaWebSite"
        connectionTimeoutInMilliseconds = "5000" 
        operationTimeoutInMilliseconds = "1000"/>
  </providers>
</sessionState>

用户登录时必须创建新的Session对象。

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        var user = await UserManager.FindAsync(model.UserName, model.Password);
        if (user != null)
        {
            if (user.EmailConfirmed == false)
                return View("_ActivationCodeManuel", user);

            await SignInAsync(user, model.RememberMe);

            var uSo = JsonConvert.SerializeObject(user);
            Session.Add(user.Id, uSo);

            return RedirectToLocal(returnUrl);
        }

        ModelState.AddModelError("", "E-posta adresinizi ya da şifrenizi hatalı girdiniz.");

    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

如果会话在redis上显示,则应该链接到登录页面,或者如果用户在另一台计算机上启动新会话,则应该显示当前的会话。 但现在只使用cookie。

    [Authorize]        
    public ActionResult Index()
    {            
        var id = User.Identity.GetUserId();         
        return View();
    }

我想我需要ovveride授权方法。它应该检查redis上的cookie和会话吗?

1 个答案:

答案 0 :(得分:1)

身份框架不依赖会话来存储任何身份验证数据,因此您必须自己实现。

我认为与Redis会话绑定的cookie失效的最佳位置是OnValidateIdentity事件。它在Startup.Auth.cs中可用,看起来像这样(默认模板):

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            // other stuff
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });    
        // other stuff

您可以实施自己的SecurityStampValidator.OnValidateIdentity版本来检查会话状态。

为了其他目的,我已将此事件搞砸了,here is the sample of my code - 只是一个如何在那里实现自己逻辑的示例。