asp.net mvc实现用户登录验证

在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;
            }
        }
}

登录页视图代码示意:


    
@using (Html.BeginForm("Login", "Login", FormMethod.Post,new { @id="submitForm"})) { //===========增加防跨站代码====================== @Html.AntiForgeryToken() //===========增加隐藏的提交url======================== @Html.HiddenFor(s => s.ReturnURL)
@Html.Label("用户名", new { @class = "labelpp" }) @Html.TextBoxFor(s => s.Username, new { @class= "inputpp" })
@Html.Label("口令", new { @class = "labelpp" }) @Html.TextBoxFor(s=>s.Password, new { @class = "inputpp" })
} @if (ViewBag.ErrorMessage != null) {
@Html.Label( "用户认证失败", new { @id = "promptMsg", @style = "color:red"})
}
@Html.Label("请检查输入", new { @id = "errorMsg", @style = "color:red" ,@type= "hidden" })

控制器中注销方法的代码:

        [HttpGet]
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            Session.Clear();
            System.Web.HttpContext.Current.Session.RemoveAll();
            
            return Redirect("/Login/Login");
        }

 

你可能感兴趣的:(asp.net)