简体   繁体   中英

Unable to get the Current.User.Identity using formsauthentication

I am new to asp.net mvc 2. I'm learning mvc by doing a test project. I am using formsauthentication to log into my website. During login I am able to log into the website but I am not getting the useridentity.

i have taken http://www.dotnetfunda.com/articles/article141.aspx as my reference website

in my webconfig file.

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

in login controller

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

in userlogoncontrol i have made changes like this. but it is not displaying username and my bin.

<%
    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") %> ]
<%
    }
%>

Did I miss anything?How can i save my user details like userid and role in cookie.

The article you have linked to is about WebForms. In ASP.NET MVC I would recommend you using a custom [Authorize] filter. Your Login looks fine. You can keep it like this. Then write a custom Authorize attribute:

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

Now decorate a controller/action with this custom attribute:

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

Now need to touch at Global.asax .

_identity = Thread.CurrentPrincipal.Identity;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM