Try our conversational search powered by Generative AI!

PrincipalInfo.Current.IsPermitted() for anonymous users

Vote:
 

Hello,

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>

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;
user?.AddIdentity(CustomRole);

I can then query the database with 

PrincipalInfo.Current.IsPermitted(CustomPermissions.Permission)

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.

#201289
Feb 12, 2019 11:39
Vote:
 

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.

#201470
Feb 20, 2019 9:45
Vote:
 

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 work
var userImpersonation = ServiceLocator.Current.GetInstance<IUserImpersonation>(); PrincipalInfo.CurrentPrincipal = userImpersonation.CreatePrincipal("some userId");
var user = PrincipalInfo.CurrentPrincipal as ClaimsPrincipal;
user.AddIdentity(claim);
 
#201688
Feb 27, 2019 8:20
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.