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

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

 <authentication mode="Forms">
<forms loginUrl="~/Authentication/Login" timeout="" />
<!--<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 > )
{
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内置的数据属性,所以能够利用前端拦截错误信息
 

MVC授权认证的更多相关文章

  1. 七天学会ASP.NET MVC (四)——用户授权认证问题

    小编应各位的要求,快马加鞭,马不停蹄的终于:七天学会 Asp.Net MVC 第四篇出炉,在第四天的学习中,我们主要了学习如何在MVC中如何实现认证授权等问题,本节主要讲了验证错误时的错误值,客户端验 ...

  2. 七天学会ASP.NET MVC (四)——用户授权认证问题 【转】

    http://www.cnblogs.com/powertoolsteam/p/MVC_four.html 小编应各位的要求,快马加鞭,马不停蹄的终于:七天学会 Asp.Net MVC 第四篇出炉,在 ...

  3. Asp.Net Core 2.0 项目实战(10) 基于cookie登录授权认证并实现前台会员、后台管理员同时登录

    1.登录的实现 登录功能实现起来有哪些常用的方式,大家首先想到的肯定是cookie或session或cookie+session,当然还有其他模式,今天主要探讨一下在Asp.net core 2.0下 ...

  4. 使用微服务架构思想,设计部署OAuth2.0授权认证框架

    1,授权认证与微服务架构 1.1,由不同团队合作引发的授权认证问题 去年的时候,公司开发一款新产品,但人手不够,将B/S系统的Web开发外包,外包团队使用Vue.js框架,调用我们的WebAPI,但是 ...

  5. API代理网关和OAuth2.0授权认证框架

    API代理网关和OAuth2.0授权认证框架 https://www.cnblogs.com/bluedoctor/p/8967951.html 1,授权认证与微服务架构 1.1,由不同团队合作引发的 ...

  6. 授权认证(IdentityServer4)

    区别 OpenId: Authentication :认证 Oauth: Aurhorize :授权 输入账号密码,QQ确认输入了正确的账号密码可以登录 --->认证 下面需要勾选的复选框(获取 ...

  7. 你还不了解基于session的授权认证吗?

    前言 在漫长的开发过程中,权限认证是一个永恒不变的话题,随着技术的发展,从以前的基于sessionId的方式,变为如今的token方式.session常用于单体应用,后来由于微服务的兴起,分布式应用占 ...

  8. IOS第三天-新浪微博 - 版本新特性,OAuth授权认证

    *********版本新特性 #import "HWNewfeatureViewController.h" #import "HWTabBarViewController ...

  9. Yii2框架RESTful API教程(二) - 格式化响应,授权认证和速率限制

    之前写过一篇Yii2框架RESTful API教程(一) - 快速入门,今天接着来探究一下Yii2 RESTful的格式化响应,授权认证和速率限制三个部分 一.目录结构 先列出需要改动的文件.目录如下 ...

随机推荐

  1. 剑指Offer 变态跳台阶

    题目描述 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级.求该青蛙跳上一个n级的台阶总共有多少种跳法.   其实就是斐波那契数列问题. 假设f(n)是n个台阶跳的次数. f(1) = ...

  2. COGS 2421.[HZOI 2016]简单的Treap 题解

    题目大意: 给定n个数及其优先级,求对应的符合最小堆性质的Treap的先序遍历. n<=500000. 解法: 目前为止我只想到了三种解法,其中第三种是正解. 1.暴力1 以优先级为关键字排序, ...

  3. Java拼接批量新增SQL语句

    StringBuffer addSql = new StringBuffer(1000); int batchSize = 50; int executeTime = 0; SimpleDateFor ...

  4. PHP socket编程需要了解的一些基本知识

    前面讲到了 fsockopen 的各种情况,其中涉及了很多其它知识,比如chunked分段传输,Keep-Alive,HTTP头字段等额外的知识,如果对这些知识一知半解,会影响对 PHP 的 sock ...

  5. Docker内部存储结构(devicemapper)解析(续)

    dm.fs 参数dm.fs可以指定容器的rootfs的文件系统,但只支持ext4/xfs: func NewDeviceSet(root string, doInit bool, options [] ...

  6. C++中的结构体

    http://zhidao.baidu.com/link?url=8OYQSKV9mvSBc6Hkf9NsLQmipSge9VCZDJQGAZZs5PCBQ54UTmK98VRmAklEEAFYu7d ...

  7. libreoffice安装

    centos7下libreoffice的安装 #下载安装包wget http://mirrors.ustc.edu.cn/tdf/libreoffice/stable/5.1.1/rpm/x86_64 ...

  8. iOS UIViewController 和 nib 相关的3个方法

    iOS UIViewController 的 awakeFromNib 以及 - (id)initWithCoder:(NSCoder *)aDecoder 和 - (instancetype)ini ...

  9. FFmpeg-20160506-snapshot-bin

    ESC 退出 0 进度条开关 1 屏幕原始大小 2 屏幕1/2大小 3 屏幕1/3大小 4 屏幕1/4大小 S 下一帧 [ -2秒 ] +2秒 ; -1秒 ' +1秒 下一个帧 -> -5秒 F ...

  10. ubuntu vsftp 安装

    1.输入sudo apt-get install vsftpd 回车 这样就安装完毕了,然后去建立一个ftp的帐号,我这里使用的是ftp. 2.输入useradd ftp 回车 输入密码 回车 这样帐 ...