I have a .NET 4.5 application with custom Identity implemented. I log in with my user, and then at some point later on, the application makes me log in again. I have verified that the auth cookie is still alive and not expired. After doing much research, it appears that the SecurityStampValidator is expiring which invalidates my user and forces another login. I have tried numerous changes, but nothing works.
Ideally, what I am looking for is to only use the auth cookie expiration, and completely disable the SecurityStampValidator. I have not found a way to do that.
I've created a custom user and user manager:
public class CustomUser : IUser<int>
public class CustomUserManager : UserManager<CustomUser, int>
This is my startup.cs:
public void Configuration(IAppBuilder app)
{
// create the data access object we are using
app.CreatePerOwinContext(() => new CustomAccountDataAccess());
// create the custom user manager
app.CreatePerOwinContext<CustomUserManager>((opt, cont) => new CustomUserManager(cont.Get<CustomAccountDataAccess>()));
// create the standard signin manager
app.CreatePerOwinContext<SignInManager<CustomUser, int>>((opt, cont) =>
new SignInManager<CustomUser, int>(cont.Get<CustomUserManager>(), cont.Authentication));
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
// use cookie authentication
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
ExpireTimeSpan = TimeSpan.FromDays(500),
Provider = new CookieAuthenticationProvider()
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<CustomUserManager, CustomUser, int>(
validateInterval: TimeSpan.FromDays(500),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),
getUserIdCallback: (id) => (id.GetUserId<int>()))
}
});
}
If I set validateInterval to some short duration like a minute or two, it works as expected, and my user is logged out after that time. I've set breakpoints in GenerateUserIdentityAsync, and it never gets called. If I set it to some high duration as above, then at some point my user gets logged out anyway. I test this by logging in, and then coming back the next day, and my user is logged out.
I've tried turning off SecurityStampValidator in my CustomUserManager, but that had no effect.
public override bool SupportsUserSecurityStamp => false;
Incidentally, I've loaded the same app code on two different web servers. One server runs .NET 4.5, and the other runs the latest .NET (at least 6.0). The server running .NET 4.5 works exactly as I want. The user is logged in, and stays logged in. On the other server, the user gets logged out as described above.
At this point, I have no idea how to change this so my user stays logged in until the cookie expires. I've seen similar issues posted here, but nothing seems to fix this for me.
I finally figured this out. I was running two web apps (one .NET 4.5 MVC, and the other .NET 6.0 Blazor Server), and neither would persist the login. I then came across this ticket:
ASP.Net Core Cookie Authentication is not persistant
Which had this comment: "another thought... Is your server storing cookie decryption keys permanently? If not, whenever the server or the app pool restarts, users will have to login again..."
Sure enough, when I tested an application pool cycle, I lost my authentication. It turns out that my .NET 4.5 application was missing machinekey from the web.config. I added that in, and it fixed the issue of losing my auth for that application.
I was also running a Blazor Server App (.NET 6.0). For that one, it does not use machinekey I needed to add DataProtection in the startup.cs:
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo("C:\storagePathtosavekey"))
.SetApplicationName("BlazorApp")
.SetDefaultKeyLifetime(TimeSpan.FromDays(500));
Adding that code fixed auth there. Things seem to be working now, with the auth persisting as I would expect.
I have a web site build using .net Framework 4.8 and MVC5 which is using Identity 2 for authentication/user management.
Now I am creating a new application for a REST API written in .net 5 using JWT authentication and I want to use the same user database for both (SQL tables accessed using Microsoft EF).
I've successfully managed to modify the schema of the users table and I can authenticate users in the new REST service but during login the password stored in the database is rehashed and updated so that it will no longer work in the old MVC5 app.
I'm trying to force the new .net 5 app to use the old (V2) .net 4.8 hashed passwords without changing them to the new V3 format. In the .net 5 app I have added the following line to the ConfigureServices(IServiceCollection services) of Startup.cs but it does not have any effect. The password still gets updated in the database, leaving the users on the old app unable to log in.
services.Configure<PasswordHasherOptions>(options => options.CompatibilityMode = PasswordHasherCompatibilityMode.IdentityV2);
I have tried to add this before and after the call to AddIdentity which looks like this:
services.AddIdentity<ApplicationUser, ApplicationRole>(options => options.SignIn.RequireConfirmedAccount = false)
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultUI()
.AddDefaultTokenProviders()
.AddClaimsPrincipalFactory<MyUserClaimsPrincipalFactory>();
It makes no difference. The PasswordHasherOptions do not appear to be effective.
I am using Autofac as my DI for the .net 5 app, if that makes any difference.
I have created a .net core 3 Web Application. I have connected it to an Azure Active Directory.
This is the first time I have used AD so please excuse my ignorance.
The problem I have is that when the user logs into the website the login process is enforcing 2FA. They are being given 14 days grace before this is enforced.
Although, personally I have no problem with 2FA, in this case we want to be able to disable it.
I have searched high and low for documentation on how to do this but many of the documents do not reflect the current design of the Azure Portal.
Is this something I can control in my Startup.cs? Which looks like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => Configuration.Bind("AzureAd", options));
services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
services.AddRazorPages();
services.AddSignalR(x =>
{
x.EnableDetailedErrors = true;
});
}
Any help would be greatly appreciated!
If you are integrated your application with Azure Active Directory, then make sure the primary and the secondary authentication is happening in Azure.
When the user try to login to the website, usually the authentication process goes to Azure AD for primary and 2FA.
Scenario 1 - 14 days grace period
Azure Active Directory Identity Protection will prompt your users to register the next time they sign in interactively and they will have 14 days to complete registration. During this 14-day period, they can bypass registration but at the end of the period they will be required to register before they can complete the sign-in process.
Scenario 2 - Disable 2FA
If you want to disable MFA for the users, you need to check the following.
Check if there are any conditional access polices are created to trigger MFA including classic policies.
Check if there are any individual MFA setting (enabled) in Azure portal.
You can disable MFA through PowerShell
i have a ASP.net Core 2.0 MVC Application and experiencing a weird problem. When using HttpContext.SignInAsync(...) to SignIn a User in my AccountsControler.cs this creates a Cookie named ".AspNetCore.Identity.Application". When later using HttpContext.SignOutAsync () to sign out the user, ASP.net Core decides to delete the cookie name "Identity.External" by setting this Cookie in the Response-Header to expire at the unix epoch.
Looks like i got something wrong with my CookieAuthentication. Anybody got an idea, where to look?
FunFact: Neither of both names is what i expected to see, since i configured a completely diffrent name for CookieAuthentication:
services.AddAuthentication (CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie (
options => {
options.Cookie.Name = "MyMagic.User";
}
);
Actually the problem seemed to be, that i used
service.AddAuthentication(...)
in this App. Looks like a ASP.net Core 1.0 migration artefact in my code.
After removing the explicit Cookie-Authentication, SignInAsync() and SignOutAsync() used the same cookie name.
Additionally, with
services.ConfigureApplicationCookie(opts => {
opts.Cookie.Name = "My.Cookie.User";
});
i was able to rename the cookie. :)
I have made a C# Asp.net Core application it's working fine. But problem is that it will automatically logout user after 10 to 20 minutes or after one operation is over then automatically user logout from the system.
I am using Azure database.
Most login schemes on .NET CORE use CookieAuthentication somehow. Most likely your problem lies there.
If you check out the documentation about cookie authentication, you'll see that you can set a timespan for which the cookie should be valid.
cookie options
app.UseCookieAuthentication(options =>
{
options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
});
Should fix your problem.
You can also make it "sliding", that means your cookie will get extended when half of the timespan has passed and the user makes a new request.