首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >视图中的MVC FormsAuthentication IsInRole不工作

视图中的MVC FormsAuthentication IsInRole不工作
EN

Stack Overflow用户
提问于 2017-07-28 09:39:14
回答 1查看 569关注 0票数 0

我正在验证一个用户:

代码语言:javascript
复制
        [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”的测试也在进行中。

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

代码语言:javascript
复制
if (ViewContext.HttpContext.User.IsInRole("Administrator"))
{
   <li class="dropdown">
...

为了让视图理解"IsInRole“,我需要做些什么吗?

这样做是可行的:

代码语言:javascript
复制
 @if (ViewContext.HttpContext.User.Identity.IsAuthenticated == false)

但是'IsInRole‘总是被计算为false。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-29 00:03:28

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

Global.asax.cs

代码语言:javascript
复制
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;
        }
    }
}

登录方法

代码语言:javascript
复制
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);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45370012

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档