前几天Insus.NET有在数据库实现过对某一字段进行加密码与解密《使用EncryptByPassPhrase和DecryptByPassPhrase对MS SQLServer某一字段时行加密和解密http://www.cnblogs.com/insus/p/5983645.html那今次Insus.NET在ASP.NET MVC实现自定义验证Authorize Attribute。

实现之前,Insus.NET对usp_Users_VeryLoginVerify修改一下,改为更好理解与使用:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[usp_Users_VeryLoginVerify]
(
@U_nbr NVARCHAR(20),
@pwd NVARCHAR(100)
)
AS
BEGIN
DECLARE @errmsg NVARCHAR(50) = N'用户名或密码错误。' IF NOT EXISTS(SELECT TOP 1 1 FROM [dbo].[Users] WHERE [U_nbr] = @U_nbr)
BEGIN
RAISERROR(@errmsg,16,1)
RETURN
END SELECT [U_nbr] AS [Account] FROM [dbo].[Users] WHERE [U_nbr] = @U_nbr AND CONVERT(NVARCHAR(100),DECRYPTBYPASSPHRASE('insus#sec!%y',[Pwd])) = @pwd IF @@ROWCOUNT <= 0
BEGIN
RAISERROR(@errmsg,16,1)
RETURN
END
END

Source Code

OK,上面是数据库方面。
接下你需要在ASP.NET MVC写程序:

使用Cookie来存储登录以及验证信息,写一个Cookie类别:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace Insus.NET.Utilities
{
public abstract class CookieBase
{
private static HttpResponse Response
{
get
{
return HttpContext.Current.Response;
}
} private static HttpRequest Request
{
get
{
return HttpContext.Current.Request;
}
} public static HttpCookie Cookie
{
get
{
return Request.Cookies["CookieBase"] as HttpCookie;
}
set
{
if (Request.Cookies["CookieBase"] != null)
{
Request.Cookies.Remove("CookieBase");
}
Response.Cookies.Add(value);
}
} public static HttpCookie NewCookie
{
get
{
return new HttpCookie("CookieBase");
}
} public static void RemoveCookie()
{
if (Cookie == null)
Response.Cookies.Remove("CookieBase");
else
Response.Cookies["CookieBase"].Expires = DateTime.Now.AddDays(-1);
}
}
}

Source Code

其实上面这个CookeBase.cs是一个能存储多对象的集合类。在真正的程序中,你想存储什么信息,可以写一个如下面的类来操作:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web; namespace Insus.NET.Utilities
{
public class SecurityBase
{
public static bool IsAuthorized
{
get
{
return CookieBase.Cookie == null ? false : bool.Parse(CookieBase.Cookie.Values["IsAuthorized"]);
}
set
{
HttpCookie httpCookie = CookieBase.Cookie == null ? CookieBase.NewCookie : CookieBase.Cookie;
httpCookie.Values["IsAuthorized"] = value.ToString();
CookieBase.Cookie = httpCookie;
}
} public static string UserName
{
get
{
return CookieBase.Cookie == null ? string.Empty : CookieBase.Cookie.Values["UserName"];
}
set
{
HttpCookie httpCookie = CookieBase.Cookie == null ? CookieBase.NewCookie : CookieBase.Cookie;
httpCookie.Values["UserName"] = value;
CookieBase.Cookie = httpCookie;
}
} public static void RemoveCooke()
{
CookieBase.RemoveCookie();
}
}
}

Source Code

接下来,我们需要创建一个验证过滤器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Insus.NET.Utilities;
using System.Web.Routing; namespace Insus.NET.Attributes
{
public class SecurityAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
return SecurityBase.IsAuthorized;
} public override void OnAuthorization(AuthorizationContext filterContext)
{
string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = filterContext.ActionDescriptor.ActionName;
base.OnAuthorization(filterContext);
} protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
var routeValue = new RouteValueDictionary {
{ "Controller", "Home"},
{ "Action", "Index"}
};
filterContext.Result = new RedirectToRouteResult(routeValue);
}
}
}

Source Code

这个过滤器SecurityAuthorizeAttribute.cs,稍后我们会在控制器中应用到它。

接下你需要写控制器了,不,我们似乎少写了一些物件,如model和Entity:

Models写好,还差一个Entity,这个实体是与数据连接的物件:

在ASP.NET MVC中,实现登录验证的演示,最少需要两个控制器,一个是给匿名用户访问的,它包含普通的页面和一些基本的操作。另一个控制器是经过验证通过之后才能访问的页面。

另一个控制器:

最后是创建视图了:

@{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title> <style type="text/css">
#logincontact label {
display: inline-block;
width: 100px;
text-align: right;
} #logincontact_submit {
padding-left: 100px;
} #logincontact div {
margin-top: 1em;
} .error {
display: none;
margin-left: 10px;
} .error_show {
color: red;
margin-left: 10px;
} input.invalid {
border: 2px solid red;
} input.valid {
border: 2px solid green;
}
</style> <script src="~/Scripts/jquery-2.2.1.js"></script> <script type="text/javascript">
////<![CDATA[
$(document).ready(function () {
$('#logincontact_Account').on('input', function () {
var input = $(this);
var is_Account = input.val();
if (is_Account) {
input.removeClass("invalid").addClass("valid");
}
else {
input.removeClass("valid").addClass("invalid");
}
}); $('#logincontact_Password').on('input', function () {
var input = $(this);
var is_Password = input.val();
if (is_Password) {
input.removeClass("invalid").addClass("valid");
}
else {
input.removeClass("valid").addClass("invalid");
}
}); $('#ButtonSignIn').click(function (event) {
var form_data = $("#logincontact").serializeArray();
var error_free = true;
for (var input in form_data) {
var element = $("#logincontact_" + form_data[input]['name']);
var valid = element.hasClass("valid");
var error_element = $("span", element.parent()); if (!valid) {
error_element.removeClass("error").addClass("error_show");
error_free = false;
}
else {
error_element.removeClass("error_show").addClass("error");
}
} if (!error_free) {
event.preventDefault();
}
else {
var obj = {};
obj.Account = $('#logincontact_Account').val(),
obj.Password = $('#logincontact_Password').val() $.ajax({
type: 'POST',
url: '/Home/LoginVerify',
dataType: 'json',
data: JSON.stringify(obj),
contentType: 'application/json; charset=utf-8',
success: function (data, textStatus) {
alert("登录成功。");
window.location.href = "/User/Index";
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
},
});
}
});
});
//]]>
</script>
</head>
<body>
<form id="logincontact" method="post" action="">
<div>
<label for="logincontact_Account">Account:</label>
<input type="text" id="logincontact_Account" name="Account" />
<span class="error">This account field is required.</span>
</div>
<div>
<label for="logincontact_Password">Password:</label>
<input type="password" id="logincontact_Password" name="Password" />
<span class="error">This password field is required.</span>
</div>
<div id="logincontact_submit">
<input id="ButtonSignIn" type="button" value="Sign In" />
</div>
</form>
</body>
</html>

Source Code

还有一个:

@{
Layout = null;
} <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-2.2.1.js"></script> <script type="text/javascript">
////<![CDATA[
$(document).ready(function () { $('#ButtonSignOut').click(function (event) {
$.ajax({
type: 'POST',
url: '/Home/SignOut',
contentType: 'application/json; charset=utf-8',
success: function (data, textStatus) {
alert("已经安全退出网站。");
window.location.href = "/Home/Index";
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
},
});
});
});
//]]>
</script>
</head>
<body>
<div>
Hi @ViewBag.UserName
<br />
<input id="ButtonSignOut" type="button" value="Sign Out" />
</div>
</body>
</html>

Source Code

结束了,来一个实时演示吧:

ASP.NET MVC自定义验证Authorize Attribute的更多相关文章

  1. ASP.NET MVC自定义验证Authorize Attribute(包含cookie helper)

    前几天Insus.NET有在数据库实现过对某一字段进行加密码与解密<使用EncryptByPassPhrase和DecryptByPassPhrase对MS SQLServer某一字段时行加密和 ...

  2. ASP.NET MVC Model验证(五)

    ASP.NET MVC Model验证(五) 前言 上篇主要讲解ModelValidatorProvider 和ModelValidator两种类型的自定义实现, 然而在MVC框架中还给我们提供了其它 ...

  3. 通过扩展改善ASP.NET MVC的验证机制[实现篇]

    原文:通过扩展改善ASP.NET MVC的验证机制[实现篇] 在<使用篇>中我们谈到扩展的验证编程方式,并且演示了本解决方案的三大特性:消息提供机制的分离.多语言的支持和多验证规则的支持, ...

  4. Asp.Net MVC 身份验证-Forms

    Asp.Net MVC 身份验证-Forms 在MVC中对于需要登录才可以访问的页面,只需要在对应的Controller或Action上添加特性[Authorize]就可以限制非登录用户访问该页面.那 ...

  5. ASP.NET MVC异步验证是如何工作的03,jquery.validate.unobtrusive.js是如何工作的

    在上一篇"ASP.NET MVC异步验证是如何工作的02,异步验证表单元素的创建"中了解了ASP.NET异步验证是如何创建表单元素的,本篇体验jquery.validate.uno ...

  6. ASP.NET MVC Model验证(四)

    ASP.NET MVC Model验证(四) 前言 本篇主要讲解ModelValidatorProvider 和ModelValidator两种类型的自定义实现,前者是Model验证提供程序,而Mod ...

  7. ASP.NET MVC Model验证(三)

    ASP.NET MVC Model验证(三) 前言 上篇中说到在MVC框架中默认的Model验证是在哪里验证的,还讲到DefaultModelBinder类型的内部执行的示意图,让大家可以看到默认的M ...

  8. ASP.NET MVC Model验证(二)

    ASP.NET MVC Model验证(二) 前言 上篇内容演示了一个简单的Model验证示例,然后在文中提及到Model验证在MVC框架中默认所处的位置在哪?本篇就是来解决这个问题的,并且会描述一下 ...

  9. ASP.NET MVC Model验证(一)

    ASP.NET MVC Model验证(一) 前言 前面对于Model绑定部分作了大概的介绍,从这章开始就进入Model验证部分了,这个实际上是一个系列的Model的绑定往往都是伴随着验证的.也会在后 ...

随机推荐

  1. Hadoop学习笔记—4.初识MapReduce

    一.神马是高大上的MapReduce MapReduce是Google的一项重要技术,它首先是一个编程模型,用以进行大数据量的计算.对于大数据量的计算,通常采用的处理手法就是并行计算.但对许多开发者来 ...

  2. 飞鱼(FlyFish)——便捷的原型在线制作工具

    关于项目原型制作,小菜先前写过一篇文章<FastUI快速界面原型制作工具>,只不过那个是用C#写的原型制作工具,但是感觉用C#写起来比较费力,而且也不太好用,经过高人指点,茅塞顿开,决定重 ...

  3. Azure PowerShell (3) 上传证书

    <Windows Azure Platform 系列文章目录> 本文介绍的是国外的Azure Global Update 2015-09-01 发现一个新的命令,在Azure PowerS ...

  4. How to use the function of assembly.

    Here are some simple conceptions that I summarized: 1, %rsp    -----  top of the stack 2, %rbp    -- ...

  5. SqlServer2008安装时提示重启计算机失败 解决办法

    问题描述: 在安装Sql Server 2008时提示重启计算机,重启之后不行,仍需要重启计算机. 如下图所示: 解决方法: 1.运行(或按键盘Win+R 组合键),输入regedit,调出注册表管理 ...

  6. Gitcafe绑定自定义域名

    之前将自己练习写作工具替换为Markdown,部署工具改为Hexo,并且将托管地搬家到GitCafe之后,便是被各种的舒爽所围绕.具体折腾的详情参见使用Hexo搭建专属Blog.她们的组合方便快捷,让 ...

  7. 基于redis实现可靠的分布式锁

    什么是锁 今天要谈的是如何在分布式环境下实现一个全局锁,在开始之前先说说非分布式下的锁: 单机 – 单进程程序使用互斥锁mutex,解决多个线程之间的同步问题 单机 – 多进程程序使用信号量sem,解 ...

  8. iOS运行时编程(Runtime Programming)和Java的反射机制对比

    运行时进行编程,类似Java的反射.运行时编程和Java反射的对比如下:   1.相同点   都可以实现的功能:获取类信息.属性设置获取.类的动态加载(NSClassFromString(@“clas ...

  9. 快速搭建php环境

    WAMP:在windows系统下搭建PHP开发环境 APPSERVER: 两种可用于开发环境的,一般用WAMP LAMP构架 Linux系统 Apache服务器管理软件 Mysql数据库 php语言 ...

  10. CRL 版本2.2.0.0发布

    重要更新: 增加了关联查询 优化了缓存查找效率 关联查询有以下两种形式 返回Select结果,结果为动态对象 将结果附加给当前对象索引值 关联查询有累加效果,可关联多个表可通过匿名对象指定返回的别名, ...