代码之家  ›  专栏  ›  技术社区  ›  Craig

MVC FormsAuthentication在视图中无效

  •  0
  • Craig  · 技术社区  · 8 年前

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

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

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

    我需要做些什么来让视图理解“IsInRole”?

    这项工作:

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

    1 回复  |  直到 8 年前
        1
  •  1
  •   Win    8 年前

    由于您自己设置了FormsAuthenticationCookie,所以需要创建Principle对象,并在内部的每个请求中将其分配给当前线程 事件

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