วันจันทร์ที่ 29 กรกฎาคม พ.ศ. 2556

Disable SimpleMembership in MVC 4

Today I need to use simple membership in web.config but SimpleMembership in MVC 4 is not simple.

First u need to custom Web.config like this
        <authentication mode="Forms">
            <forms loginUrl="~/Account/Login" timeout="2880" >
                <credentials passwordFormat="Clear">
                    <user name="test" password="test"/>
                </credentials>
            </forms>
        </authentication>

add this to AppSettings
<add key="enableSimpleMembership" value="false"/>

and in AccountController disable InitializeSimpleMembership
//[InitializeSimpleMembership]

now for Login use this for realy simple life.

        // POST: /Account/Login

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login( LoginModel model, string returnUrl )
        {
            //if (ModelState.IsValid && WebSecurity.Login( model.UserName, model.Password, persistCookie: model.RememberMe ))
            //{
            //    return RedirectToLocal( returnUrl );
            //}
            if (!ValidateLogOn( model.UserName, model.Password ))
                return View( model );

            FormsAuthentication.SetAuthCookie( model.UserName, model.RememberMe );

            if (!String.IsNullOrEmpty( returnUrl ))
                return Redirect( returnUrl );
            else
                return RedirectToAction( "LogOn" );

            //// If we got this far, something failed, redisplay form
            //ModelState.AddModelError( "", "The user name or password provided is incorrect." );
            //return View( model );
        }

        //Add Custom Validate for validate user and pass in Web.config
        private bool ValidateLogOn( string userName, string passWord )
        {
            if (string.IsNullOrEmpty( userName ))
                ModelState.AddModelError( "username", "User name required" );

            if (string.IsNullOrEmpty( passWord ))
                ModelState.AddModelError( "password", "Password required" );

            if (ModelState.IsValid && !FormsAuthentication.Authenticate( userName, passWord ))
                ModelState.AddModelError( "_FORM", "Wrong user name or password" );

            return ModelState.IsValid;
        }
        //End Custom Validate

        //
        // POST: /Account/LogOff

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            //WebSecurity.Logout();

            //return RedirectToAction( "Index", "Home" );

            FormsAuthentication.SignOut();
            return RedirectToAction( "LogOn" );
        }

ไม่มีความคิดเห็น: