DB queried each time AuthUserSession.HasRole/HasPermission referenced?

For me, it seems the authRepo is making a database call every time AuthUserSession.HasRole() or AuthUserSession.HasPermission() via IAuthRepo.GetUserAuth().

Is this intended or is there a way to avoid that? I see there are two collection properties Permissions, Roles in the AuthUserSession object but they are always empty. Is there a way to set those when the user is authenticated?

Can you provide the configuration of your UserAuth Repository? If your AuthRepo uses Distinct Role/Permission tables or it implements IManageRoles then it will check the external tables when querying for roles/permissions.

One way to avoid it is to use JWTs which embed Users roles/permission in the JWT Token so it won’t need to query the AuthRepo.

We are using standard OrmLiteAuthRepository. Roles are not in separate tables, they are pulled from the UserAuth table.

we have subclassed AuthUserSession to add an additional property to the session. Perhaps we should override HasRole and HasPermission like so (just adding additional check to make sure roles are empty before having authRepo fetch them):

public override bool HasRole(string role, IAuthRepository authRepo)
        {
            if (!FromToken && this.Roles.IsNullOrEmpty()) //If populated from a token it should have the complete list of roles
            {
                var managesRoles = authRepo as IManageRoles;
                if (managesRoles != null)
                {
                    if (UserAuthId == null)
                        return false;

                    return managesRoles.HasRole(this.UserAuthId, role);
                }
            }

            return this.Roles != null && this.Roles.Contains(role);
        }

Perhaps this could be implemented in the SS code base by changing the implementation of HasRole to something like this:

        public virtual bool HasRole(string role, IAuthRepository authRepo, bool reload = true)
        {
            if(reload)
            {
                if (!FromToken) //If populated from a token it should have the complete list of roles
                {
                    var managesRoles = authRepo as IManageRoles;
                    if (managesRoles != null)
                    {
                        if (UserAuthId == null)
                            return false;

                        return managesRoles.HasRole(this.UserAuthId, role);
                    }
                }
            }

            return this.Roles != null && this.Roles.Contains(role);
        }

Yeah using OrmLiteAuthRepository would re-check the database. So you’d need to override HasRole() / HasPermission() to change its behavior to just check the Roles on the Users Session, e.g:

public override bool HasRole(string role, IAuthRepository authRepo) => 
    this.Roles != null && this.Roles.Contains(role);