2016年11月9日 星期三

ASP .NET MVC 登入驗證 FormsAuthentication

  1. [AllowAnonymous] //此Class不驗證
  2. public class AccountController : BaseController
  3. {
  4. [HttpPost]
  5. public ActionResult LoginGo(Login form)
  6. {
  7. Session.RemoveAll();
  8. Session["LoginInfo"] = null;
  9. LoginData loginData = new LoginData();
  10. try
  11. {
  12. if (ValidateLogin(form))
  13. {
  14. //驗證成功(失敗則重新登入)
  15. loginData.loginStatus = "00";
  16. loginData.userId = form.userId;
  17. loginData.userName = "使用者名稱";
  18. //表單驗證開始
  19. FormsAuthenticationTicket authTicket = LoginProcess(form.userId);
  20. //加密Ticket
  21. string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
  22. //建立Cookie
  23. HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
  24. //將建立的Cookie寫入Cookie
  25. Response.Cookies.Add(authCookie);
  26. return RedirectToAction("Login", "Account");
  27. }
  28. else
  29. {
  30. return RedirectToAction("Login", "Account");
  31. }
  32. }
  33. catch (Exception ex)
  34. {
  35. return RedirectToAction("Login", "Account");
  36. }
  37. }
  38. private bool ValidateLogin(Login form)
  39. {
  40. //DB驗證,AD驗證寫在此
  41. return true;
  42. }
  43. //將登入資訊寫入Ticket
  44. private FormsAuthenticationTicket LoginProcess(string userId)
  45. {
  46. string roles = "test";
  47. FormsAuthenticationTicket authTicket =
  48. new FormsAuthenticationTicket(
  49. 1,
  50. userId,
  51. DateTime.Now,
  52. DateTime.Now.AddMinutes(20),
  53. false,
  54. roles//寫入角色之後角色權限使用
  55. );
  56. return authTicket;
  57. }
  58. }
所有的Controller都繼承BaseController,驗證寫在BaseController[Authorize],若Method或Class不需要驗證則加上[AllowAnonymous]
  1. [Authorize]
  2. public class BaseController : Controller
  3. {
  4. protected static NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();
  5. }
Web.config 配置