Search code examples
asp.net-mvcrazorlogin-controlcustom-membershipprovider

ASP.NET MVC3 + JQuery Mobile: Custom Membershipprovider (no logincontrol)


I'm currently rebuilding one of my ASP.NET [Webform] Sites with JQuery Mobile + MVC (Razor Viewengine).

Now I'm having problem porting the Membershipprovider to the new technique, because I can't use Webcontrols (LoginControl) anymore. The Membership-provider itself works great, but I can't seem to 'initialize' it by 'logging in' without the common Web-LoginControl.

Are there any ways to reproduce this with HTML-Controls? (I'm new to MVC and jquery mobile, Google + Search couldn't help me)

Thanks in advance


Solution

  • You can do everything manually. This code will create the auth ticket cookie.

    FormsAuthenticationTicket authTicket =
                        new FormsAuthenticationTicket(1,
                        model.UserName,
                        DateTime.Now,
                        DateTime.Now + SecurityWebConfig.FormAuthTicketTimeout,
                        false,
                        userData);
                    string encTicket = FormsAuthentication.Encrypt(authTicket);
                    HttpCookie faCookie =
                      new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                    faCookie.Path = FormsAuthentication.FormsCookiePath;
                    Response.Cookies.Add(faCookie);
                    Response.Redirect("~/");
    

    Then this event in your global.asax.cs will load it back in.

    protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            // Get the authentication cookie
            string cookieName = FormsAuthentication.FormsCookieName;
            HttpCookie authCookie = Context.Request.Cookies[cookieName];
    
            // If the cookie can't be found, don't issue the ticket
            if (authCookie == null) return;
    
            // Get the authentication ticket and rebuild the principal 
            // & identity
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
    
            CustomUser currentUser = new CustomUser(authTicket);
    
            GenericPrincipal userPrincipal =
              new GenericPrincipal(currentUser, new string[] { "User" });
            Context.User = userPrincipal;
    
        }
    

    Hopefully that will get you started.