简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM