MVC FormsAuthentication IsInRole in View not working

大兔子大兔子 提交于 2020-02-08 06:28:05

问题


I am authenticating a user:

        [Route("Login"), HttpPost, AllowAnonymous]
        public LoginViewModelResponse Login(LoginViewModelRequest data)
        {

            if(!Membership.ValidateUser(data.Username, data.Password))
            {
                return new LoginViewModelResponse
                {
                    DisplayMessage = "Invalid Username/Password!",
                    IsSuccess = false,
                    RedirectUrl = "/Home/"
                };
            }


            FormsAuthentication.SetAuthCookie(data.Username, false);
            ClaimsIdentity identity = new GenericIdentity(data.Username);


            var roles = "Administrator,User".Split(',');
           // var client = AuthorisationService.instance.GetAuthenticatedUser();// new ClientService().GetClientById(1);
            var principle = new GenericPrincipal(identity, roles);

            HttpContext.Current.User = principle;
            System.Threading.Thread.CurrentPrincipal = principle;

            if (User.IsInRole("Administrator"))
            {
                var b = 1;
            }
            return new LoginViewModelResponse
            {
                IsSuccess = true,
                DisplayMessage = "OK",
                RedirectUrl = "/Home/"
            };
        }

And the test for 'IsInRole' is working.

However, I have the following in my View (_layout), and the check for Administrator fails.

if (ViewContext.HttpContext.User.IsInRole("Administrator"))
{
   <li class="dropdown">
...

Is there something I need to do to allow the View to understand "IsInRole"?

This works:

 @if (ViewContext.HttpContext.User.Identity.IsAuthenticated == false)

But 'IsInRole' always evaluated to false.


回答1:


Since you set FormsAuthentication cookie by yourself, you'll need to create Principle object and assign it to current thread on every request inside AuthenticateRequest event.

Global.asax.cs

public class Global : HttpApplication
{
    protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        HttpCookie decryptedCookie =
            Context.Request.Cookies[FormsAuthentication.FormsCookieName];
        if (decryptedCookie != null)
        {
            FormsAuthenticationTicket ticket =
                FormsAuthentication.Decrypt(decryptedCookie.Value);

            var identity = new GenericIdentity(ticket.Name);
            var roles = ticket.UserData.Split(',');
            var principal = new GenericPrincipal(identity, roles);

            HttpContext.Current.User = principal;
            Thread.CurrentPrincipal = HttpContext.Current.User;
        }
    }
}

Sign-In method

public void SignIn(string username, bool createPersistentCookie)
{
    var now = DateTime.UtcNow.ToLocalTime();
    TimeSpan expirationTimeSpan = FormsAuthentication.Timeout;

    var ticket = new FormsAuthenticationTicket(
        1 /*version*/,
        username,
        now,
        now.Add(expirationTimeSpan),
        createPersistentCookie,
        "" /*userData*/,
        FormsAuthentication.FormsCookiePath);

    var encryptedTicket = FormsAuthentication.Encrypt(ticket);

    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, 
        encryptedTicket)
    {
        HttpOnly = true,
        Secure = FormsAuthentication.RequireSSL,
        Path = FormsAuthentication.FormsCookiePath
    };

    if (ticket.IsPersistent)
    {
        cookie.Expires = ticket.Expiration;
    }
    if (FormsAuthentication.CookieDomain != null)
    {
        cookie.Domain = FormsAuthentication.CookieDomain;
    }

    Response.Cookies.Add(cookie);
}


来源:https://stackoverflow.com/questions/45370012/mvc-formsauthentication-isinrole-in-view-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!