Не могу проверить роль пользователя. User.IsInRole возвращает false - PullRequest
1 голос
/ 23 марта 2019

Я пытаюсь проверить роль пользователя в представлении:

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

, но получаю все время false, хотя

User.Identity.IsAuthenticated
User.Identity.Name

возвращает true и name.

Служба проверки подлинности моих форм:


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);
    }
}

и звонки

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

1 Ответ

0 голосов
/ 24 марта 2019

Исправлено добавлением в 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);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...