Search code examples
asp.net-mvcasp.net-membershipdatabase-connectionmembership-provider

ASP MVC Membership without a database


Is it possible to use WebSecurity or SimpleMembersshipProvider without a database? This is mainly because my web server would be consuming all the logic from a "central server" instead of accessing directly to the database.


Solution

  • Sure. Please see how to implement a custom membership provider: http://www.codeproject.com/Articles/165159/Custom-Membership-Providers

    Basically what you need to do is inherit the MembershipProvider class and implement basic methods like ValidateUser and the like and once finished register the new provider in web.config. You can use any data store you like.

    Another option is to handle user authentication manually and using FormsAuthentication.Authenticate() to send auth cookies with user requests. This method also works with the [Authorize] filter, if you want I can send you a code sample.

    Edit:

    public class CustomAuthorizeFilter : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var authenCookie = httpContext.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
            if (authenCookie == null) return false;
    
            return true;
        }
    
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new RedirectResult("/");
        }
    }
    

    Login method:

    var ticket = new FormsAuthenticationTicket(1, // version 
                                       token, // user name
                                       DateTime.Now, // create time
                                       DateTime.Now.AddDays(1), // expire time
                                       model.RememberMe, // persistent
                                       ""); // user data, such as roles
    var strEncryptedTicket = FormsAuthentication.Encrypt(ticket);
    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, strEncryptedTicket);
    Response.Cookies.Add(cookie);