zoukankan      html  css  js  c++  java
  • MVC授权认证

    处于安全性考虑,MVC可以完成授权认证,授权认证的方式如下:

    1、配置Config文件,设置登录页面:

     <authentication mode="Forms">
          <forms loginUrl="~/Authentication/Login" timeout="2880" />
          <!--<forms cookieless="UseUri" loginUrl="~/Authentication/Login"></forms>-->
        </authentication>

    2、Action添加授权认证属性Authorize:

            [Authorize]
            public ActionResult Index()
            {  
                EmployeeBusinessLayer empBal = new EmployeeBusinessLayer();
                List<Employee> employees=empBal.GetEmployees();
                List<EmployeeViewModel> empviewModels = new List<EmployeeViewModel>();
                foreach (Employee emtp in employees)
                {
                    EmployeeViewModel vmEmp = new EmployeeViewModel();
                    vmEmp.EmployeeName = emtp.FirstName + " " + emtp.LastName;
                    vmEmp.Salary = emtp.Salary.ToString("C");
                    if (emtp.Salary > 15000)
                    {
                        vmEmp.SalaryColor = "yellow";
                    }
                    else
                    {
                        vmEmp.SalaryColor = "green";
                    }
                    empviewModels.Add(vmEmp);
                }
    
                EmployeeListViewModel currlistmodel = new EmployeeListViewModel();
    
    
                currlistmodel.UserName = User.Identity.Name;
                currlistmodel.Employees = empviewModels;
                return View(currlistmodel);
            }

    备注:显示当前用户信息,User.Identity.Name获取

    3、设置授权认证。

    FormsAuthentication.SetAuthCookie(udemail.UserName, false);//表示通过身份认证

    FormsAuthentication.SignOut();//表示注销身份认证

    Login页面代码如下:

    @using MyMVC3Demo.Models;
    @model UserDetails
    @{
        Layout = null;
    }
    
    <!DOCTYPE html>
    
    <html>
    <head>
        <title>Login</title>
        <script src="../../Scripts/jquery-1.8.0.min.js" type="text/javascript"></script>
        <script src="../../Scripts/jquery.validate.js" type="text/javascript"></script>
        <script src="../../Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>
    </head>
    <body>
        <div>
            @Html.ValidationMessage("CredentialError", new { style = "color:red;" })
            @using(Html.BeginForm("DoLogin","Authentication",FormMethod.Post))
            {
                @Html.LabelFor(c=>c.UserName)
                @Html.TextBoxFor(x=>x.UserName)
                @Html.ValidationMessageFor(x => x.UserName)
                <br />
                @Html.LabelFor(c => c.Password)
                @Html.PasswordFor(c => c.Password)    
                <br />
                <input type="submit" name="BtnSubmit" value="Login" />
            }
        </div>
    </body>
    </html>
     备注1: @Html.TextBoxFor(x=>x.UserName)转换为HTML代码<input id="UserName" name="UserName" type="text" value="" />

       2:@using (Html.BeginForm("DoLogin", "Authentication", FormMethod.Post)){ }

    转换为HTML代码<form action="/Authentication/DoLogin" method="post"> </form>

    Control代码如下:
            public ActionResult Login()
            {
                return View();
            }
    
            public ActionResult Logout()
            {
                FormsAuthentication.SignOut();
                return RedirectToAction("Login");
            }
    
            [HttpPost]
            public ActionResult DoLogin(UserDetails udemail)
            {
                if (ModelState.IsValid)
                {
                    EmployeeBusinessLayer bll = new EmployeeBusinessLayer();
                    if (bll.IsValidUser(udemail))
                    {
                        FormsAuthentication.SetAuthCookie(udemail.UserName, false);
                        return RedirectToAction("Index", "Employee");
                    }
                    else
                    {
                        ModelState.AddModelError("CredentialError", "Invalid Username or Password");
                        return View("Login");
                    }
                }
                else {
                    return View("Login");
                }
            }

    ModelState.IsValid是对Model类型的校验;

    ModelState.AddModelError(),自定义错误类型,便于前台显示;

    @Html.ValidationMessage("CredentialError", new { style = "color:red;" })

    补充:

    用客户端显示错误信息

    1、选择“Manage Nuget packages”,点击在线查找”jQuery Unobtrusive“,安装”Microsoft jQuery Unobtrusive Valiadtion“

    2、引用一下JS

    • jQuery-Someversion.js
    • jQuery.valiadte.js
    • jquery.validate.unobtrusive

    3、利用Unobtrusive展示错误消息的主要原因在HtmlHelp类能够将

     @Html.TextBoxFor(x=>x.UserName)
     @Html.ValidationMessageFor(x=>x.UserName)
    转换成
    <input data-val="true" data-val-length="UserName length should be between 2 and 7" data-val-length-max="7" data-val-length-min="2" id="UserName" name="UserName" type="text" value="" />
    <span class="field-validation-error" data-valmsg-for="UserName" data-valmsg-replace="true"> </span>
    data-val-length又是Unbtrusive内置的数据属性,所以能够利用前端拦截错误信息
     
  • 相关阅读:
    JournalNode的作用
    mysql57重新安装后无法再次启动mysql57服务“本地计算机上的MySQL服务启动后停止。某些服务在未由其他服务或程序使用时将自动。”--解决方法
    oracle基础语法
    MYSQL 8.0.11 安装过程及 Navicat 链接时遇到的问题
    MySQL 字符串函数:字符串截取
    java基础总结
    mysql 排名
    mysql——查询重复数据,及删除重复数据只保留一条数据
    松软科技课堂:jQuery 效果
    松软科技课堂:jQuery 效果
  • 原文地址:https://www.cnblogs.com/xibei666/p/4998981.html
Copyright © 2011-2022 走看看