Can't check user role. User.IsInRole returning false

Muller

I'm trying to check a user role in View:

@if (User.IsInRole("User"))

but getting all time false, although

User.Identity.IsAuthenticated
User.Identity.Name

returns true and name.

My forms authentication service:


public static void SignIn(string userName, string role, bool createPersistentCookie)
{
    FormsAuthenticationTicket authTicket = new
        FormsAuthenticationTicket(1,
                            userName,
                            DateTime.Now,
                            DateTime.Now.AddMinutes(30), 
                            createPersistentCookie,
                            role);

    string encTicket = FormsAuthentication.Encrypt(authTicket);
    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
    {
        Expires = authTicket.Expiration,
        Path = FormsAuthentication.FormsCookiePath
    };

    if (HttpContext.Current != null)
    {
        HttpContext.Current.Response.Cookies.Add(cookie);
    }
}

and calling

FormsAuthenticationService.SignIn(model.UserName, "User", true);
Muller

Fixed by adding to Global.asax :

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
    if (authCookie == null || authCookie.Value == "")
        return;

    FormsAuthenticationTicket authTicket;
    try
    {
        authTicket = FormsAuthentication.Decrypt(authCookie.Value);
    }
    catch
    {
        return;
    }

    string[] roles = authTicket.UserData.Split(';');

    if (Context.User != null)
        Context.User = new GenericPrincipal(Context.User.Identity, roles);
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related