asp.net mvc實現使用者登入驗證
阿新 • • 發佈:2019-02-08
在Asp.net中實現登入驗證可以設定使用者登入驗證頁面為預設的路由處理路徑,訪問其它頁面時候,在頁面控制器中增加 CheckAuthority屬性,要求進行登入認證後才能訪問相關控制器,CheckAuthority屬性定義程式碼如下示例:
//==============屬性繼承自AuthorizeAttribute,需重寫OnAuthorization方法=========== public class CheckAuthority: AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { if (HttpContext.Current.Session["UserID"] == null || !HttpContext.Current.Request.IsAuthenticated) { if (filterContext.HttpContext.Request.IsAjaxRequest()) { filterContext.HttpContext.Response.StatusCode = 302; //Found Redirection to another page. Here- login page. Check Layout ajaxError() script. filterContext.HttpContext.Response.End(); } else { filterContext.Result = new RedirectResult(System.Web.Security.FormsAuthentication.LoginUrl + "?ReturnUrl=" + filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.RawUrl)); } } else { //Code HERE for page level authorization } } }
CheckAuthority使用程式碼如下示例:
[CheckAuthority]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
登入認證控制器程式碼如下示意:
public class LoginController : Controller { //================獲取登入頁面======================== [HttpGet] public ActionResult Login(string returnURL) { return View(); } //============提交登入資訊,要求加入防跨站屬性宣告 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Login(LoginVM Logininfo) { if (Logininfo.Username == "admin" && Logininfo.Password == "admin") { Session["UserID"] = Logininfo.Username; Logininfo.ReturnURL = "/Home/Index"; SignInRemember(Logininfo.Username, true); return RedirectToLocal(Logininfo.ReturnURL); } else { ViewBag.ErrorMessage = "使用者認證失敗,請檢查您的賬戶資訊"; return View(); } } //GET: SignInAsync private void SignInRemember(string userName, bool isPersistent = false) { // Clear any lingering authencation data FormsAuthentication.SignOut(); // Write the authentication cookie FormsAuthentication.SetAuthCookie(userName, isPersistent); } private ActionResult RedirectToLocal(string returnURL = "") { try { // If the return url starts with a slash "/" we assume it belongs to our site // so we will redirect to this "action" if (!string.IsNullOrWhiteSpace(returnURL) && Url.IsLocalUrl(returnURL)) return Redirect(returnURL); // If we cannot verify if the url is local to our host we redirect to a default location return RedirectToAction("Index", "Home"); } catch { throw; } } }
登入頁檢視程式碼示意:
<body> <div class="pop-div"> <div class="log-close"></div> <div class="log-cloud cloud1"></div> <div class="log-cloud cloud2"></div> <label class="prompt-label">使用者登入</label> @using (Html.BeginForm("Login", "Login", FormMethod.Post,new { @id="submitForm"})) { //===========增加防跨站程式碼====================== @Html.AntiForgeryToken() //===========增加隱藏的提交url======================== @Html.HiddenFor(s => s.ReturnURL) <div class="rows"> @Html.Label("使用者名稱", new { @class = "labelpp" }) @Html.TextBoxFor(s => s.Username, new { @class= "inputpp" }) </div> <div class="rows"> @Html.Label("口令", new { @class = "labelpp" }) @Html.TextBoxFor(s=>s.Password, new { @class = "inputpp" }) </div class="rows"> <button type ="button" class="loginBtn" id="btnIn">Login</button> } @if (ViewBag.ErrorMessage != null) { <div class="rows">@Html.Label( "使用者認證失敗", new { @id = "promptMsg", @style = "color:red"})</div> } <div class="rows">@Html.Label("請檢查輸入", new { @id = "errorMsg", @style = "color:red" ,@type= "hidden" })</div> </div> </body>
控制器中登出方法的程式碼:
[HttpGet]
public ActionResult Logout()
{
FormsAuthentication.SignOut();
Session.Clear();
System.Web.HttpContext.Current.Session.RemoveAll();
return Redirect("/Login/Login");
}