在ASP.Net MVC中进行身份认证

 这种表单验证的方式适用于本地用户凭据,其优点是容易设置和便于管理。

@using (Html.BeginForm("Login", "Home"))
{ 
    <input type="text" name="adminName" />
    <br />
    <input type="password" name="pwd" />
    <input type="submit" name="name" value="登录" />
}
using System.Web;
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Login()
        {
            string name = HttpContext.Request.Form["adminName"];
            string pwd = HttpContext.Request.Form["pwd"];
            //拿到用户输入的账号密码之后需要去后台数据库进行验证,若验证通过则继续。
            //先将通过验证的用户名存放到session中。
            Session["user"] = name;
            //为当前用户名提供一个身份证票据,并将该票证添加到Cookie。
            System.Web.Security.FormsAuthentication.SetAuthCookie(name, false);
            return Content("123");
        }

        [Authorize]
        public ActionResult DoSth()
        {
            //如果使用了Authorize特性,则不需要使用下面这个判断。
            if (this.User.Identity.IsAuthenticated)//如果存在身份认证标识
            {
                //string adminName = this.User.Identity.Name;//获取写入的adminName。
            }
            return View();
        }

        [Authorize]
        public ActionResult LoginOut()
        {
            System.Web.Security.FormsAuthentication.SignOut();//这里删除凭据之后,需要将页面跳转到登录页面才行,否则this.User.Identity.IsAuthenticated仍然为true
            Session["user"] = null;//清楚session
            return RedirectToAction("Index", "Home");
        }
    }
}

在Web.config文件中进行相关配置。过期时间为30分钟。跳转页面

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    
    <authentication mode="Forms">
      <forms loginUrl="~/Home/Index" timeout="30"></forms>
    </authentication>

如果微软提供的基本认证无法满足需求的时候,可以写自己的特性来继承AuthorizeAttribute类。

    public class CheckPermissionAttribute : AuthorizeAttribute
    {
        //复写AuthorizeAttribute类中的虚方法AuthorizeCore,该方法会在授权认证时执行。
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (Users != "james")
            {
                return false;//这里return false表示认证授权未通过。
            }
            if (Roles != "NBAPlayer")
            {
                return false;
            }
            //这里可以使用httpContext对象来获取客户端发过来的所有的请求信息,根据这些信息,我们可以进行后续的认证。
            return base.AuthorizeCore(httpContext);
        }
    }

在Action中的使用

        [CheckPermission(Users = "james", Roles = "NBAPlayer")]
        public ActionResult Index()
        {
            return Content("This is the Index action on the Home Controller");
        }

书上的大神不建议自己写类去实现IAuthorizationFilter。因为实现编写安全性的代码可能会存在一些遗漏的缺陷或未经测试的角落,会给应用程序留下安全漏洞。

 微软提供的默认authorize特性在小项目和中型的对权限控制没有复杂要求的项目里已经够用了。缺点是项目开发前得确定好业务的各种角色,因为要以“硬编码”的方式写在接口方法上。后期如果要修改一个接口的所属角色,只有重新修改代码。

//这里可
原文地址:https://www.cnblogs.com/vichin/p/12245387.html