Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get HttpContext.Current.User as custom principal in mvc c#

I am trying to use the HttpContext.Current.User with my own class that inherits from IPrincipal. I am not exactly sure why..

var lIdentity = new UserIdentity(lFormsTicket);
var lRoles = lAuthUser.Roles.Select(x => x.Role.ToString()).ToArray();
var lPrincipal = new GenericPrincipal(lIdentity, lRoles);

System.Web.HttpContext.Current.User = lIdentity;

Right after I am setting this it works. But if I do another request on the site, it says that it cannot cast it. Am I missing something here?

like image 311
Angelika S Michel Avatar asked Jan 31 '26 11:01

Angelika S Michel


1 Answers

You are setting User as IIdentity when it should be IPrincipal

var lIdentity = new UserIdentity(lFormsTicket);
var lRoles = lAuthUser.Roles.Select(x => x.Role.ToString()).ToArray();
var lPrincipal = new GenericPrincipal(lIdentity, lRoles);

System.Web.HttpContext.Current.User = lPrincipal;

You will probably need to use your own custom IPrincipal

public class UserPrincipal : IPrincipal {
    string[] roles;

    public UserPrincipal (IIdentity identity, param string[] roles) {
        this.Identity = identity;
        this.roles = roles ?? new string[]{ };
    }

    public IIdentity Identity { get; private set; }

    public bool IsInRole(string role) {
        return roles.Any(s => s == role);
    }
}

I'm not sure if the application will complain as it may be expecting a ClaimsPrincipal derived type.

like image 75
Nkosi Avatar answered Feb 03 '26 01:02

Nkosi