2017-12-27 559 views
0

我有一个项目,有asp.net MVC和asp.net WebApi。为什么我的asp.net身份的用户会自动注销

我不知道为什么用户会自动注销,例如当我关闭浏览器和15分钟后,我发现我需要重新登录,并且在将用户重定向到银行网站以进行付款后,银行网站再次将用户重定向到我的网站需要重新登录。

我用asp.net身份验证cookie,下面是我StartUp.cs文件代码:

public class Startup 
{ 
    public string Issuer { get; set; } 
    public void Configuration(IAppBuilder app) 
    { 
     Issuer = "http://localhost:37993/"; 

     ConfigureOAuthTokenGeneration(app); 
     ConfigureOAuthTokenConsumption(app); 

     app.UseCors(CorsOptions.AllowAll); 

     GlobalConfiguration.Configure(WebApiConfig.Register); 
     AreaRegistration.RegisterAllAreas(); 
     //app.UseWebApi(GlobalConfiguration.Configuration); 
     RouteConfig.RegisterRoutes(RouteTable.Routes); 
     //app.UseMvc(RouteConfig.RegisterRoutes); 

     //ConfigureWebApi(GlobalConfiguration.Configuration); 

    } 
    private void ConfigureOAuthTokenGeneration(IAppBuilder app) 
    { 
     app.CreatePerOwinContext(() => new LeitnerContext()); 
     app.CreatePerOwinContext<LeitnerUserManager>(LeitnerUserManager.Create); 
     app.CreatePerOwinContext<LeitnerRoleManager>(LeitnerRoleManager.Create); 

     // Plugin the OAuth bearer JSON Web Token tokens generation and Consumption will be here 

     app.UseCookieAuthentication(new CookieAuthenticationOptions() 
     { 
      AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, 
      LoginPath = new Microsoft.Owin.PathString("/User/Login"), 
      ExpireTimeSpan = TimeSpan.FromDays(15), 
      Provider = new CookieAuthenticationProvider 
      { 
       OnApplyRedirect = ctx => 
       { 
        if (!IsForApi(ctx.Request)) 
        { 
         ctx.Response.Redirect(ctx.RedirectUri); 
        } 
       } 
      } 
     }); 
     OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions() 
     { 
      AllowInsecureHttp = true, 
      TokenEndpointPath = new PathString("/api/token"), 
      AccessTokenExpireTimeSpan = TimeSpan.FromDays(15), 
      Provider = new LeitnerOAuthProvider(), 
      AccessTokenFormat = new LeitnerJwtFormat(Issuer), 
     }; 
     app.UseOAuthAuthorizationServer(options); 
     //app.UseJwtBearerAuthentication(options); 
     //app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); 
     //app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); 

    } 

    private bool IsForApi(IOwinRequest request) 
    { 
     IHeaderDictionary headers = request.Headers; 
     return ((headers != null) && ((headers["Accept"] == "application/json") || (request.Path.StartsWithSegments(new PathString("/api"))))); 
    } 

    private void ConfigureOAuthTokenConsumption(IAppBuilder app) 
    { 
     var a = AudiencesStore.AudiencesList["LeitnerAudience"]; 
     string audienceId = a.ClientId;// ConfigurationManager.AppSettings["as:AudienceId"]; 
     byte[] audienceSecret = TextEncodings.Base64Url.Decode(a.Base64Secret/*ConfigurationManager.AppSettings["as:AudienceSecret"]*/); 

     // Api controllers with an [Authorize] attribute will be validated with JWT 
     app.UseJwtBearerAuthentication(
      new JwtBearerAuthenticationOptions 
      { 
       AuthenticationMode = AuthenticationMode.Active, 
       AllowedAudiences = new[] { audienceId }, 
       IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[] 
       { 
        new SymmetricKeyIssuerSecurityTokenProvider(Issuer, audienceSecret) 
       } 
      }); 
    } 
} 

有谁知道为什么这个问题呢?

+0

您的身份验证cookie在浏览器/提琴手中看起来如何?是否有任何机会会话cookie? –

+0

@mohsen,你的数据库中的任何机会是securitystamp字段为空?你能否确认一次 – Webruster

+0

@Webruster db中的securitystamp是什么?我不知道如何asp.net身份正常工作。任何tutorila正确学习它的地方?我如何使用secutrystamp? – mohsen

回答

1

用户注销的原因是由于验证表单验证数据和视图状态数据时出错。它可能发生的原因不同,包括在托管服务中使用Web Farm。您应该在您的项目中检查<machineKey>webconfig

如果没有<machineKey>webconfig,请尝试在您的加入webconfig这段代码<system.web>后:

​​

有从那里你可以生成机键一些在线工具。您可以检查thisthis

您可以从this链接了解关于机器密钥的更多信息。

0

也许你ExpireTimeSpan = TimeSpan.FromDays(15)被忽略..

我用的时间跨度是这样的:

Provider = new CookieAuthenticationProvider 
      { 
      OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
         validateInterval: TimeSpan.FromMinutes(15), 
         regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) 
      }, 
      SlidingExpiration = false, 
      ExpireTimeSpan = TimeSpan.FromMinutes(30) 

增加从配置遗漏码。 另外,如果您有“记住我”选项,请确保您已在登录方法中配置它。

var login = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout: false); 
+0

我用你的解决方案,但它仍然不工作 – mohsen

+0

我忘了一些我在应用中使用的代码..更新了答案。 –

0

“由于此代码,15分钟后自动注销”。

TimeSpan.FromDays(15) 
正常

如果忽略该代码,你会得到的结果你想要或 ,该值由60 * 24 = 1440( - 19天分钟)设置。 所以常见的到期时间是一天。 但您将其设置为15分钟,以便发生问题。