Answer the question
In order to leave comments, you need to log in
When to get ASP.NET MVC user roles?
Good evening!
There is an entity "Role" in the Roles database (RoleId, RoleName). There is an entity user User (UserId, UserName, ...), and there is a connection UsersRoles (UserId, RoleId).
Accordingly, an ASP.NET MVC application has its own controller, BaseController: Controller, which implements the following override of the standard IPrincipal to its own IAppPrincipal:
protected virtual new AppUserPrincipal User
{
get { return new AppUserPrincipal(base.User); }
}
var userCode = User.Code;
ViewBag.UserName = User.Firstname;
bool access = User.IsInRoles("Admin, SuperAdmin");
Answer the question
In order to leave comments, you need to log in
In Identity 2.0, by default, cookies are updated every 30 minutes, saying that the password has changed or something else checks, and it also updates roles.
Change to a shorter time.
Caching Role Information
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question