视图中的MVC FormsAuthentication IsInRole无法正常工作

时间:2017-07-28 09:39:14

标签: c# asp.net asp.net-mvc forms-authentication

我正在验证用户身份:

        [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/"
            };
        }

并且测试了IsInRole'正在努力。

但是,我的View(_layout)中有以下内容,并且管理员检查失败。

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

我是否需要做些什么来让View了解&#34; IsInRole&#34;?

这有效:

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

但是&#39; IsInRole&#39;总是评价为假。

1 个答案:

答案 0 :(得分:1)

由于您自己设置了FormsAuthentication cookie,因此您需要创建Principle对象,并在 AuthenticateRequest 事件中的每个请求上将其分配给当前线程。

<强>的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;
        }
    }
}

登录方式

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