2017-12-27 3 views
0

asp.net MVC 및 asp.net WebApi가있는 프로젝트가 있습니다.내 asp.net identity -user가 자동으로 로그 아웃하는 이유

사용자가 자동으로 로그 아웃하는 이유를 모르겠습니다. 예를 들어 브라우저를 닫고 15 분이 지나면 은행 웹 사이트를 다시 리디렉션 할 때 은행 웹 사이트로 사용자를 리디렉션 한 후 다시 로그인해야합니다. 내 웹 사이트에 다시 로그인해야합니다. 이 문제가 왜

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) 
       } 
      }); 
    } 
} 

사람이 알고 있나요 :

내가 아래에있는 내 StartUp.cs에 파일 코드, asp.net ID 인증 쿠키를 사용합니까?

+0

브라우저의 인증 쿠키는 어떻게 보이나요? 어떤 세션 쿠키에 의한 것입니까? –

+0

@mohsen, 귀하의 DB에 securitystamp 필드가 null 일 가능성이 있습니까? 한번 확인해 주시겠습니까 – Webruster

+0

@Webruster DB에 securitystamp는 무엇입니까? 나는 어떻게 asp.net 정체성이 정확하게 작동하는지 khow하지 않는다. tutorila가 그것을 올바르게 배울 어디에서? 나는 어떻게 secutrystamp를 사용할 수 있는가? – mohsen

답변

1

사용자가 로그 오프하는 이유는 양식 인증 데이터 및 뷰 상태 데이터의 유효성 검사 오류 때문입니다. 호스팅 서비스에서 웹 팜을 사용하는 것을 비롯한 여러 가지 이유로 인해 발생할 수 있습니다. 웹 구성에서 <machineKey>을 확인해야합니다. 당신이 당신의 webconfig<machineKey>이없는 경우

, 당신의 webconfig<system.web> 후이 코드 조각을 추가하려고 :

당신이 기계의 키를 생성 할 수있는 일부 온라인 도구가 있습니다
<machineKey 
     validationKey="someValue" 
     decryptionKey="someValue" 
     validation="SHA1" decryption="AES"/> 

. 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) 

추가 구성에서 누락 된 코드입니다. 또한 '내 계정 정보 기억'옵션이있는 경우 로그인 방법으로 구성했는지 확인하십시오.

+0

인 경우 해결책을 사용했으나 여전히 작동하지 않습니다 – mohsen

+0

일부를 깜박했습니다. 응용 프로그램에서 사용하는 코드 .. 대답을 업데이트했습니다. –

0

"15 분 후 자동으로 로그 아웃"은이 코드로 인해 발생합니다. 정상에서

TimeSpan.FromDays(15) 

이 코드를 생략하면, 당신은 결과를 얻을 것이다 당신이 원하는 또는 ,이 값은 60 * 24 = 1440 (- 일일 분)에 의해 설정된다. 일반적인 만료 시간은 하루입니다. 하지만 문제가 발생하도록 15 분으로 설정했습니다.

관련 문제