2016年11月9日 星期三

ASP .NET MVC 登入驗證 FormsAuthentication


[AllowAnonymous] //此Class不驗證
public class AccountController : BaseController
{
    [HttpPost]
    public ActionResult LoginGo(Login form)
    {
        Session.RemoveAll();
        Session["LoginInfo"] = null;
        LoginData loginData = new LoginData();
        try
        {
            if (ValidateLogin(form))
            {
                //驗證成功(失敗則重新登入)
                loginData.loginStatus = "00";
                loginData.userId = form.userId;
                loginData.userName = "使用者名稱";

                //表單驗證開始
                FormsAuthenticationTicket authTicket = LoginProcess(form.userId);
                //加密Ticket
                string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                //建立Cookie
                HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                //將建立的Cookie寫入Cookie
                Response.Cookies.Add(authCookie);

                return RedirectToAction("Login", "Account");
            }

            else
            {
                return RedirectToAction("Login", "Account");
            }
        }
        catch (Exception ex)
        {
            return RedirectToAction("Login", "Account");
        }
    }

    private bool ValidateLogin(Login form)
    {
        //DB驗證,AD驗證寫在此 
        return true;
    }
    
    //將登入資訊寫入Ticket
    private FormsAuthenticationTicket LoginProcess(string userId)
    {
        string roles = "test";
        FormsAuthenticationTicket authTicket = 
            new FormsAuthenticationTicket(
                    1,
                    userId,
                    DateTime.Now,
                    DateTime.Now.AddMinutes(20),
                    false,
                    roles//寫入角色之後角色權限使用
                );
        return authTicket;
    }
}
所有的Controller都繼承BaseController,驗證寫在BaseController[Authorize],若Method或Class不需要驗證則加上[AllowAnonymous]
[Authorize]
public class BaseController : Controller
{
    protected static NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();
}
Web.config 配置

沒有留言:

張貼留言