问题
I have a project that have asp.net MVC and asp.net WebApi.
I don't know why User log out automatically, for example when I close browser and after 15 minutes I see that I need to login again and after I redirect user to bank website for payment when the bank website redirect user again to my web site it need to login again.
I use asp.net identity authentication cookie, below is in my StartUp.cs file code:
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)
}
});
}
}
Does anyone know why this problem is there?
回答1:
The reason for users logging off is because of error in the validation of forms-authentication data and view-state data. It could happen for different reasons including using web farm in hosting services.You should check <machineKey>
in your project webconfig.
If you don't have <machineKey>
in your webconfig
, try adding this piece of code after <system.web>
in your webconfig
:
<machineKey
validationKey="someValue"
decryptionKey="someValue"
validation="SHA1" decryption="AES"/>
There are some online tools from where you can generate machine key. You can check this and this.
You can learn more about machine key from this link.
回答2:
Maybe your ExpireTimeSpan = TimeSpan.FromDays(15)
is being ignored..
I use the TimeSpan like this:
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(15),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
},
SlidingExpiration = false,
ExpireTimeSpan = TimeSpan.FromMinutes(30)
Added the missing code from the configuration. Also, if you have the option 'Remember me' make sure you have it configured in the login method.
var login = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout: false);
回答3:
"Logging out automatically after 15 mins" happens due to this code.
TimeSpan.FromDays(15)
If you omit this code, you will get the result you want or in normal, this value is set by 60 * 24 = 1440 (mins - 1 day). So common expiration time is one day. But you set it 15 minutes so that problem occurred.
来源:https://stackoverflow.com/questions/47994611/why-my-asp-net-identity-user-will-log-out-automatically