W
W
WhiteNinja2017-01-11 17:58:37
ASP.NET
WhiteNinja, 2017-01-11 17:58:37

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); }
}

So that later in any controller, for example HomeController: BaseController, you can refer to the "Current User" object:
var userCode = User.Code;
ViewBag.UserName = User.Firstname;

bool access = User.IsInRoles("Admin, SuperAdmin");

Question - Where to fill in user roles?
1 - Once during login, adding roles via Claims? But then, if the list of user roles changes while working with the application, the user will still not have these roles in fact until he logs in again.
2 - Each time with a new request to the page, make a request to the database and take the user's roles. Is this considered normal practice?
I really need advice on these matters!
Thanks in advance for any help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MrDywar Pichugin, 2017-01-11
@Dywar

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 question

Ask a Question

731 491 924 answers to any question