无法使用 formsauthentication 获取 Current.User.Identity

本文关键字:Current User Identity 获取 formsauthentication | 更新日期: 2023-09-27 17:56:02

我是 asp.net mvc 2 的新手。我正在通过做一个测试项目来学习 mvc。我正在使用表单身份验证登录我的网站。在登录期间,我可以登录网站,但我没有得到用户身份。

我已 http://www.dotnetfunda.com/articles/article141.aspx 作为我的参考网站

在我的网络配置文件中。

<authentication mode="Forms">
      <forms loginUrl="~/Home/login" defaultUrl="~/Home/login" cookieless="UseCookies" slidingExpiration="true" timeout="20" />
</authentication>

在登录控制器中

public ActionResult Login(LogOnModel logon)
{
    if (ModelState.IsValid)
    {
        if (FormsService.SignIn(logon.UserName, logon.Password) == true)
        {
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, // version 
                                                    FormsService.Username, // user name
                                                    DateTime.Now, // create time
                                                    DateTime.Now.AddSeconds(30), // expire time
                                                    false, // persistent
                                                    FormsService.Role,
                                                    FormsAuthentication.FormsCookiePath); // user data, such as roles
            string hashCookies =   FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);
            Response.Cookies.Add(cookie);
            if (FormsService.Role == "Brand")
            {
                return RedirectToAction("Index", "Creative");
            }
            else if (FormsService.Role == "Creative")
            {
                return RedirectToAction("Index", "Creative");
            }
        }
    }
    return View();
}

在UserlogonControl中,我进行了这样的更改。但它没有显示用户名和我的垃圾箱。

<%
    if (HttpContext.Current.User.Identity.IsAuthenticated)
    {
%>
        Welcome <b><%= Html.Encode(Page.User.Identity.Name) %></b>!
        [ <%= Html.ActionLink("Log Off", "LogOff", "Account") %> ] |
<%
        if(HttpContext.Current.User.IsInRole("Brand"))
        {
%>
        [ <%= Html.ActionLink("my bin", "Bin", "Brand") %> ] |
<%
        }
        else if (HttpContext.Current.User.IsInRole("Creative"))
        {
%>
         [ <%= Html.ActionLink("my bin", "Bin", "Creative") %> ] |
<%
        }
    }
    else 
    {
%> 
        [ <%= Html.ActionLink("Log On", "LogOn", "Account") %> ]
<%
    }
%>

我错过了什么吗?如何在 Cookie 中保存我的用户详细信息,例如用户 ID 和角色。

无法使用 formsauthentication 获取 Current.User.Identity

您链接到的文章是关于WebForms的。在MVC ASP.NET 中,我建议您使用自定义[Authorize]过滤器。您的Login看起来不错。你可以保持这样。然后编写自定义授权属性:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (isAuthorized)
        {
            var cookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (cookie != null)
            {
                var ticket = FormsAuthentication.Decrypt(cookie.Value);
                var roles = ticket.UserData.Split(',');
                var identity = new GenericIdentity(ticket.Name);
                httpContext.User = new GenericPrincipal(identity, roles);
            }
        }
        return isAuthorized;
    }
}

现在使用此自定义属性修饰控制器/操作:

[MyAuthorize]
public ActionResult Foo()
{
    // here the this.User property will represent the custom principal
    ...
}

现在需要触摸Global.asax.

_identity = Thread.CurrentPrincipal.Identity;