2017-12-27 553 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分鐘,以便發生問題。