为什么我的 asp.net 身份 - 用户会自动注销
Why my asp.net identity -user will log out automatically
我有一个项目有 asp.net MVC 和 asp.net WebApi。
我不知道为什么用户会自动注销,例如当我关闭浏览器并在 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)
}
});
}
}
有谁知道为什么会出现这个问题?
也许你的ExpireTimeSpan = TimeSpan.FromDays(15)
被忽略了..
我这样使用 TimeSpan:
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(15),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
},
SlidingExpiration = false,
ExpireTimeSpan = TimeSpan.FromMinutes(30)
添加了配置中缺少的代码。
此外,如果您有选项 'Remember me',请确保您已在登录方法中配置它。
var login = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout: false);
用户注销的原因是表单验证数据和视图状态数据的验证错误。它可能由于不同的原因而发生,包括在托管 services.You 中使用网络场应该检查项目 webconfig 中的 <machineKey>
。
如果您的 webconfig
中没有 <machineKey>
,请尝试在 webconfig
中的 <system.web>
之后添加这段代码:
<machineKey
validationKey="someValue"
decryptionKey="someValue"
validation="SHA1" decryption="AES"/>
有一些在线工具可以生成机器密钥。您可以查看 this and this.
您可以从 this link 了解更多关于机器密钥的信息。
"Logging out automatically after 15 mins" 由于此代码而发生。
TimeSpan.FromDays(15)
如果你省略这段代码,你会得到你想要的结果或者
通常,此值设置为 60 * 24 = 1440(分钟 - 1 天)。
所以常见的到期时间是一天。
但是你设置了15分钟,所以出现了问题。
我有一个项目有 asp.net MVC 和 asp.net WebApi。
我不知道为什么用户会自动注销,例如当我关闭浏览器并在 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)
}
});
}
}
有谁知道为什么会出现这个问题?
也许你的ExpireTimeSpan = TimeSpan.FromDays(15)
被忽略了..
我这样使用 TimeSpan:
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(15),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
},
SlidingExpiration = false,
ExpireTimeSpan = TimeSpan.FromMinutes(30)
添加了配置中缺少的代码。 此外,如果您有选项 'Remember me',请确保您已在登录方法中配置它。
var login = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout: false);
用户注销的原因是表单验证数据和视图状态数据的验证错误。它可能由于不同的原因而发生,包括在托管 services.You 中使用网络场应该检查项目 webconfig 中的 <machineKey>
。
如果您的 webconfig
中没有 <machineKey>
,请尝试在 webconfig
中的 <system.web>
之后添加这段代码:
<machineKey
validationKey="someValue"
decryptionKey="someValue"
validation="SHA1" decryption="AES"/>
有一些在线工具可以生成机器密钥。您可以查看 this and this.
您可以从 this link 了解更多关于机器密钥的信息。
"Logging out automatically after 15 mins" 由于此代码而发生。
TimeSpan.FromDays(15)
如果你省略这段代码,你会得到你想要的结果或者 通常,此值设置为 60 * 24 = 1440(分钟 - 1 天)。 所以常见的到期时间是一天。 但是你设置了15分钟,所以出现了问题。