本文介绍了MVC FormsAuthentication IsInRole在视图中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在验证用户身份

        [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"的测试正在工作.

And the test for 'IsInRole' is working.

但是,我的视图(_layout)中包含以下内容,并且对Administrator的检查失败.

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

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

我需要做些什么来使View理解"IsInRole"吗?

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

这有效:

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

但是'IsInRole'总是评估为false.

But 'IsInRole' always evaluated to false.

推荐答案

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

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

登录方式

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

这篇关于MVC FormsAuthentication IsInRole在视图中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 18:53