I defined couple of virtual roles and some permission types in the system I am working on. The virtual roles are there in order to assign permissions to the roles using Permissions for Functions. After doing these I can assign specific permissions for the user role.
<virtualRolesaddClaims="true"> <providers> (Other Episerver roles) <addname="CustomRole"type="EPiServer.Security.MappedRole, EPiServer.Framework"roles="CustomRole"mode="Any" /> </providers> </virtualRoles>
<virtualRolesaddClaims="true"> <providers> (Other Episerver roles)
<addname="CustomRole"type="EPiServer.Security.MappedRole, EPiServer.Framework"roles="CustomRole"mode="Any" /> </providers> </virtualRoles>
The virtual roles are assigned to CurrentPrinciple under runtime by adding a Claim to the user. The claim is defined as:
public static ClaimsIdentity CustomRole => new ClaimsIdentity(new
new Claim(ClaimTypes.Role, "CustomRole")
And added to user by
var user = EPiServer.Security.PrincipalInfo.CurrentPrincipal as ClaimsPrincipal;
I can then query the database with
and it works as expected as long as I am logged in as Episerver admin. However, IsPermitted function returns always false if the user is anoynmous even though the user has the claim "CustomRole".
Am I missing something in order to use IsPermitted function for anonymous users?
Thanks in advance.
You want to include Anonymous users in your MappedRole?
If so, you could add the Anonymous role to the mapped role, like this:
<add name="CustomRole" type="EPiServer.Security.MappedRole, EPiServer.Framework "roles="CustomRole, Anonymous" mode="Any" />
That way you do not need to add your CustomRole claim to Anonymous users in code.
Here's how I solved the issue. You need to override the CurrentPrincipal object by a new principal by CreatePrincipal method. It is then possible to use IsPermitted method on those users.
//create a principal using user id, otherwise IsPermitted does not workvar userImpersonation = ServiceLocator.Current.GetInstance<IUserImpersonation>();
PrincipalInfo.CurrentPrincipal = userImpersonation.CreatePrincipal("some userId"); var user = PrincipalInfo.CurrentPrincipal as ClaimsPrincipal;user.AddIdentity(claim);