Cookie身份验证无法维护登录

时间:2015-03-25 16:54:39

标签: asp.net-mvc session-cookies

我正试图让用户保持登录网站的方式,但过了一段时间(几个小时),用户需要再次登录。

这是我正在使用的代码:

    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            ExpireTimeSpan = TimeSpan.FromDays(30),
            SlidingExpiration = true
        });

        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        #region Facebook Authentication

            var facebookAuthenticationOptions = new FacebookAuthenticationOptions
            { 
                AppId = Util.GetConfigValue("FacebookAppID"),
                AppSecret = Util.GetConfigValue("FacebookAppSecret"),
                SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie
            };

            "email,user_about_me,user_birthday,user_hometown,user_location,user_website,user_relationships,user_mobile_phone"
                .Split(',')
                .ToList()
                .ForEach(scope => facebookAuthenticationOptions.Scope.Add(scope));

            facebookAuthenticationOptions.Provider = new FacebookAuthenticationProvider()
            {
                OnAuthenticated = async context =>
                {
                    context.Identity.AddClaim(new Claim("FacebookAccessToken", context.AccessToken));

                    foreach (var claim in context.User)
                    {
                        var claimType = string.Format("urn:facebook:{0}", claim.Key);
                        var claimValue = claim.Value.ToString();

                        if (!context.Identity.HasClaim(claimType, claimValue))
                            context.Identity.AddClaim(new Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
                    }
                }
            };

            app.UseFacebookAuthentication(facebookAuthenticationOptions);

        #endregion
    }

以下是AccountController的代码:

    // occurs when user authorize app in facebook
    public async Task<ActionResult> Callback(string returnUrl)
    {
        var result = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);

        if (result == null || result.Identity == null)
        {
            TempData[Constants.ALERT] = "Error";
            return RedirectToAction("Index", "Home");
        }

        // insert or update user info in database
        var user = userService.GenerateUser(result.Identity.Claims);

        if (!user.Active || user.IsLocked)
        {
            TempData[Constants.ALERT] = "Error";
            return RedirectToAction("Index", "Home");
        }

        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        var identity = CreateClaimsIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
        AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity);

        return RedirectToLocal(returnUrl);
    }

    private ClaimsIdentity CreateClaimsIdentity(User user, string authenticationType)
    {
        var result = new ClaimsIdentity(authenticationType, ClaimTypes.Name, ClaimTypes.Role);
        result.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString(), "http://www.w3.org/2001/XMLSchema#string"));
        result.AddClaim(new Claim(ClaimTypes.Name, user.Mail, "http://www.w3.org/2001/XMLSchema#string"));
        result.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"));
        result.AddClaim(new Claim("AspNet.Identity.SecurityStamp", Guid.NewGuid().ToString()));
        result.AddClaim(new Claim(Constants.SUPER_USER, user.Super.ToString()));

        return result;
    }

这里是web.config:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
  <connectionStrings>

    <add name="QueroShowConn" connectionString="Data Source=..." providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />

    <add key="FacebookAppID" value="..." />
    <add key="FacebookAppSecret" value="..." />
  </appSettings>
  <system.web>
    <customErrors mode="On">
      <error statusCode="404" redirect="/Error/NotFound" />
      <error statusCode="403" redirect="/Error/Authentication" />
    </customErrors>
    <compilation targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <globalization enableClientBasedCulture="true" uiCulture="auto:pt-BR" culture="auto:pt-BR" />
  </system.web>
  <system.webServer>
    <httpErrors errorMode="Custom">
      <remove statusCode="403"/>
      <remove statusCode="404"/>
      <error statusCode="403" responseMode="ExecuteURL" path="/Error/Authentication"/>
      <error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound"/>
    </httpErrors>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="FormsAuthenticationModule"/>
    </modules>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Ninject" publicKeyToken="c7192dc5380945e7" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.2.0.0" newVersion="3.2.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Practices.ServiceLocation" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.3.0.0" newVersion="1.3.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.AspNet.Identity.Core" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

关于发生了什么的任何想法?

0 个答案:

没有答案