Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Login fails after changing password ASP.NET Core

I'm using ASP.NET Core 1.0 and the identity stuff to authenticate and authorize the users. It all works fine except one single thing:

If the user resets or changes his password, he can't sign-in with the new credentials until the ASP.NET App is restarted. Means the new passwords are successfully saved in the database, but the Method _signInManager.PasswordSignInAsync() doesn't use the current data, but old one. It seems there is something like a cache in the EF Core or in the SignInManager/UserStore.

Sign-in after registration works also fine, it is just a problem after reset or change of the passwords.

like image 867
Juergen Gutsch Avatar asked Mar 11 '23 19:03

Juergen Gutsch


2 Answers

I too discovered a problem with my authentication middleware using a stale DbContext.

One solution was to refresh the user in the auth middleware's identity resolver with the following line of code:

await _dbContext.Entry(userToVerify).ReloadAsync();

Following this, I was able to verify the user's credentials against up-to-date data.

like image 138
matt-ankerson Avatar answered Mar 14 '23 17:03

matt-ankerson


Found the cause of that problem: Auth is done in a separate MiddleWare which has a wrong initialization and uses an old EF DbContext.

Using the DbContext with DI is a huge problem in ASP.NET Core. The DbContext should be used in a pretty small scope, defined with a simple using statement. Unfortunately the ASP.NET Core identity uses a DbContext which is registered in the DI. The better solution would be to register just a DbContext factory to the DI, to create a small scoped DbContext overtime you need it.

like image 20
Juergen Gutsch Avatar answered Mar 14 '23 17:03

Juergen Gutsch