Session is always null in virtual role

Ian
Ian
Vote:
 

I'm trying to create a new, virtual role that checks for a particular key to be present within a user's session, but the session object is always null. Here's a simplified version of the virtual role. What am I doing wrong?

public class CustomSessionRole : EPiServer.Security.VirtualRoleProviderBase
{
    public override bool IsInVirtualRole(IPrincipal principal, object context)
    {
        // HttpContext.Current.Session is always null
        if (HttpContext.Current == null || HttpContext.Current.Session == null) return false;

        // Never fires
        return HttpContext.Current.Session["someKey"] != null;
    }
}

The virtual role is being added in the web.config's <virtualRoles> section as follows:

<add name="CustomSession" type="MyNamespace.CustomSessionRole, MyDLL" mode="Any" />
#260727
Aug 17, 2021 14:13
valdis - Aug 20, 2021 18:36
Is session object present in other places in the website (like controller)?
Ian - Aug 23, 2021 14:15
@valdis - Yes, the session is present in the controller, view, web API calls, etc.
Vote:
 

Hi Ian

My guess would be that you see no session state, because your roles are enumerated before the session state is made available (for your HttpContext object). In this lifecycle documentation, AuthorizeRequest is listed AcquireRequestState, which means you won't have access to session state.

Two alternative suggestions (I prefer the last one, myself):

  • Wrap your logic in a visitor group criteria, create a visitor group and use that group when you set access rights.
  • Put a boolean flag in a claim on the user's Principal, so you can easily check it in your CustomSessionRole.

Hope it helps you out.

#261186
Aug 27, 2021 14:48
* 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.