Search code examples
asp.net-coreauthorizationasp.net-identity

Why doesnt [Authorize] fail when AspNetUser.IsEnabled is changed to False?


My application uses ASP.NET Core Identity to manage users, authentication and authorization

What I have noticed is that when you set IsEnabled = 0 (false) on a user in the database, the [Authorize] attribute will continue to allow the user access.

The above presumes the user was already authenticated (logged in) when IsEnabled was set to false.

Is this normal behaviour or have I misconfigured something? I realize that the user wont be able to log in again after their authentication cookie has expired, but Im hoping to find a way to immediately prevent that user access

A similar issue arises when the user's roles are changed in the database.


Solution

  • When the user logs in they receive an access token / cookie with claims, etc.

    This is stored on the client and submitted with each request. The Authorization framework in AspNet.Core will perform authorization based on the contents of the access token / cookie presented. Therefore any changes to the database in respect of the user will not be honoured until a new token is created based on that new information in the database.

    To override this and perform database checks (or cache inspection) during authorization, one approach would be to implement your own custom authorization:

    https://code-maze.com/custom-authorize-attribute-aspnetcore/

    https://learn.microsoft.com/en-us/aspnet/core/security/authorization/iauthorizationpolicyprovider?view=aspnetcore-7.0