ASP. NET MVC4 Forms logon verification, mvc4forms
Web. config Configuration:
In the <system. web> section:
<authentication mode="Forms"> <forms loginUrl="~/Auth/Account/Login" timeout="2880" /></authentication>
Logon code:
/// <Summary> /// log on /// </summary> public static bool Login (string userName, string userPwd) {MySqlHelper dbHelper = new MySqlHelper (); sys_user userModel = dbHelper. findBySql <sys_user> (string. format ("select * from Sys_User where UserName = '{0}'", userName); if (userModel! = Null) {if (userModel. userPwd. toUpper () = MD5Helper. encrypt (userPwd) {FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (userName, false, 120); string encryptedTicket = FormsAuthentication. encrypt (ticket); HttpCookie authCookie = new HttpCookie (FormsAuthentication. formsCookieName, encryptedTicket); HttpContext. current. response. cookies. add (authCookie); return true ;}} return false ;}View Code
Exit logon code:
/// <Summary >/// log out /// </summary> public static void LoginOut () {FormsAuthentication. SignOut ();}View Code
Determine whether a user is logged on:
/// <Summary> /// determine whether to log on. /// </summary> public static bool IsLogin {get {return HttpContext. Current. User. Identity. IsAuthenticated ;}}View Code
Get logon User:
/// <Summary> /// obtain the logon user /// </summary> public static sys_user LoginUser {get {if (HttpContext. current. user. identity. isAuthenticated) {string cookieName = FormsAuthentication. formsCookieName; HttpCookie authCookie = HttpContext. current. request. cookies [cookieName]; FormsAuthenticationTicket authTicket = FormsAuthentication. decrypt (authCookie. value); string userName = authTicket. name; MySqlHelper dbHelper = new MySqlHelper (); return dbHelper. findBySql <sys_user> (string. format ("select * from SYS_USER where UserName = '{0}'", userName);} return null ;}}View Code
Action skip logon verification using AllowAnonymous:
[AllowAnonymous] public ActionResult Login () {return View ();}View Code
Use Authorize to log on to the Controller that requires authentication, or add it to the ControllerBase you write:
[Authorize] public class ControllerBase: ControllerView Code