asp.net MVC 通用登录验证模块
用法:
还是希望读者把源码看懂,即可运用自如。重点是,为什么有个UserType!!!
登录用户信息:
namespace MVCCommonAuth
{
[Serializable]
public class LoginUser
{
";
public int ID { get; set; }
public string UserName { get; set; }
public string Roles { get; set; }
public DateTime Expires { get; set; }
public readonly static string CookieNamePrefix = "authcookie";
public void Login(string userType, string domain = null, string path = null)
{
var keyName = CookieNamePrefix + userType;
var json = JsonConvert.SerializeObject(this);
var value = EncryptString(json, DESKEY);
HttpCookie cookie = new HttpCookie(keyName, value);
cookie.Expires = Expires;
if (!string.IsNullOrWhiteSpace(domain))
{
cookie.Domain = domain;
}
if (path != null)
{
cookie.Path = path;
}
HttpContext.Current.Items[keyName] = this;
HttpContext.Current.Response.Cookies.Add(cookie);
}
/// <summary>
/// 从cookie读取用户信息
/// </summary>
/// <param name="cookieName"></param>
private static LoginUser BuildUser(string keyName)
{
var cookie = HttpContext.Current.Request.Cookies[keyName];
if (cookie != null && !string.IsNullOrEmpty(cookie.Value))
{
try
{
var json = DecryptString(cookie.Value, DESKEY);
var loginuser = JsonConvert.DeserializeObject<LoginUser>(json);
if (loginuser != null)
{
if (loginuser.Expires >= DateTime.Now)
{
return loginuser;
}
}
}
catch
{
//do nothing
}
}
return null;
}
public static LoginUser GetUser(string userType)
{
var keyName = CookieNamePrefix + userType;
if (!HttpContext.Current.Items.Contains(keyName))
{
var user = BuildUser(keyName);
HttpContext.Current.Items[keyName] = user;
return user;
}
else
{
return HttpContext.Current.Items[keyName] as LoginUser;
}
}
public static int GetUserID(string userType)
{
var user = GetUser(userType);
if (user != null)
return user.ID;
;
}
/// <summary>
/// 退出cookie登录
/// </summary>
public static void Logout(string userType)
{
var keyName = CookieNamePrefix + userType;
HttpCookie cookie = new HttpCookie(keyName, string.Empty);
cookie.Expires = DateTime.Now.AddMonths(-);
HttpContext.Current.Response.Cookies.Add(cookie);
}
#region 字符串加密
/// <summary>
/// 利用DES加密算法加密字符串(可解密)
/// </summary>
/// <param name="plaintext">被加密的字符串</param>
/// <param name="key">密钥(只支持8个字节的密钥)</param>
/// <returns>加密后的字符串</returns>
private static string EncryptString(string plaintext, string key)
{
//访问数据加密标准(DES)算法的加密服务提供程序 (CSP) 版本的包装对象
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
des.Key = ASCIIEncoding.ASCII.GetBytes(key); //建立加密对象的密钥和偏移量
des.IV = ASCIIEncoding.ASCII.GetBytes(key); //原文使用ASCIIEncoding.ASCII方法的GetBytes方法
byte[] inputByteArray = Encoding.Default.GetBytes(plaintext);//把字符串放到byte数组中
MemoryStream ms = new MemoryStream();//创建其支持存储区为内存的流
//定义将数据流链接到加密转换的流
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, , inputByteArray.Length);
cs.FlushFinalBlock();
//上面已经完成了把加密后的结果放到内存中去
StringBuilder ret = new StringBuilder();
foreach (byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
ret.ToString();
return ret.ToString();
}
/// <summary>
/// 利用DES解密算法解密密文(可解密)
/// </summary>
/// <param name="ciphertext">被解密的字符串</param>
/// <param name="key">密钥(只支持8个字节的密钥,同前面的加密密钥相同)</param>
/// <returns>返回被解密的字符串</returns>
private static string DecryptString(string ciphertext, string key)
{
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
];
; x < ciphertext.Length / ; x++)
{
, ), ));
inputByteArray[x] = (byte)i;
}
des.Key = ASCIIEncoding.ASCII.GetBytes(key); //建立加密对象的密钥和偏移量,此值重要,不能修改
des.IV = ASCIIEncoding.ASCII.GetBytes(key);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, , inputByteArray.Length);
cs.FlushFinalBlock();
//建立StringBuild对象,createDecrypt使用的是流对象,必须把解密后的文本变成流对象
StringBuilder ret = new StringBuilder();
return System.Text.Encoding.Default.GetString(ms.ToArray());
}
catch (Exception)
{
return "error";
}
}
#endregion
}
}
Action验证过滤器:
namespace MVCCommonAuth
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class AuthFilterAttribute : ActionFilterAttribute
{
public AuthFilterAttribute() { }
public AuthFilterAttribute(string roles,string userType) {
this.Roles = roles;
this.UserType = userType;
}
public bool Allowanonymous { get; set; }
public string Roles { get; set; }
public string Users { get; set; }
public string UserType { get; set; }
public sealed override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (Allowanonymous) return;
if (IsAuth()) return;
UnauthorizedRequest(filterContext);
}
public sealed override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
}
public sealed override void OnResultExecuting(ResultExecutingContext filterContext)
{
base.OnResultExecuting(filterContext);
}
public sealed override void OnResultExecuted(ResultExecutedContext filterContext)
{
base.OnResultExecuted(filterContext);
}
private bool IsAuth()
{
var user = LoginUser.GetUser(UserType);
if (user != null)
{
return AuthorizeCore(user.UserName, user.Roles);
}
else
{
return false;
}
}
private void UnauthorizedRequest(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
UnauthorizedAjaxRequest(filterContext);
else
UnauthorizedGenericRequest(filterContext);
}
protected virtual bool AuthorizeCore(string userName, string userRoles)
{
var separator = new char[] { ',' };
var options = StringSplitOptions.RemoveEmptyEntries;
if (!string.IsNullOrWhiteSpace(Users))
{
return Users.Split(separator, options).Contains(userName);
}
if (!string.IsNullOrWhiteSpace(Roles))
{
var allowRoles = Roles.Split(separator, options);
var hasRoles = userRoles.Split(separator, options);
foreach (var role in hasRoles)
{
if (allowRoles.Contains(role))
{
return true;
}
}
return false;
}
return true;
}
protected virtual void UnauthorizedGenericRequest(ActionExecutingContext filterContext)
{
//根据Roles、Users、UserType信息分别跳转
filterContext.Result = new RedirectResult("/Account/login?returnurl=" + filterContext.HttpContext.Request.Url.PathAndQuery);
}
protected virtual void UnauthorizedAjaxRequest(ActionExecutingContext filterContext)
{
var acceptTypes = filterContext.HttpContext.Request.AcceptTypes;
if (acceptTypes.Contains("*/*") || acceptTypes.Contains("application/json"))
{
filterContext.Result = , msg = "nologin" }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
else
{
filterContext.Result = new ContentResult { Content = "nologin" };
}
}
}
}
asp.net MVC 通用登录验证模块的更多相关文章
- ASP.NET MVC通用权限管理系统(响应布局)源码更新介绍
一.asp.net mvc 通用权限管理系统(响应布局)源码主要以下特点: AngelRM(Asp.net MVC)是基于asp.net(C#)MVC+前端bootstrap+ztree+lodash ...
- ASP.NET MVC 用户登录Login
ASP.NET MVC 用户登录Login一.先来看个框架例子:(这个是网上收集到的) 第一步:创建一个类库ClassLibrary831. 第二步:编写一个类实现IHttpM ...
- asp.net MVC通用分页组件 使用方便 通用性强
asp.net MVC通用分页组件 使用方便 通用性强 该分页控件的显示逻辑: 1 当前页面反色突出显示,链接不可点击 2 第一页时首页链接不可点击 3 最后一页时尾页链接不可点击 4 当前页面左 ...
- ASP.NET MVC使用AuthenticationAttribute验证登录
首先,添加一个类AuthenticationAttribute,该类继承AuthorizeAttribute,如下: using System.Web; using System.Web.Mvc; n ...
- asp.net MVC通用权限管理系统-响应式布局-源码
一.Angel工作室简单通用权限系统简介 AngelRM(Asp.net MVC Web api)是基于asp.net(C#)MVC+前端bootstrap+ztree+lodash+jquery技术 ...
- Asp.Net Mvc通用后台管理系统,bootstrap+easyui+权限管理+ORM
产品清单: 1.整站源码,非编译版,方便进行业务的二次开发 2.通用模块与用户等基础数据的数据库脚本 3.bootstrap3.3.1 AceAdmin模板源码 4.easyui1.3.5源码 5.F ...
- 【MVC】ASP.NET MVC之数据验证
前端传到后端数据的不可信任性,DRY("Don't Repeat Yourself") 设计原则.MVC3.0出了后端数据验证特性,鼓励你只定义一次功能或行为,然后在应用程序中各处 ...
- ASP.NET MVC Cookie 身份验证
1 创建一个ASP.NET MVC 项目 添加一个 AccountController 类. public class AccountController : Controller { [HttpGe ...
- ASP.NET MVC的客户端验证:jQuery验证在Model验证中的实现
在简单了解了Unobtrusive JavaScript形式的验证在jQuery中的编程方式之后,我们来介绍ASP.NET MVC是如何利用它实现客户端验证的.服务端验证最终实现在相应的ModelVa ...
随机推荐
- arcgis server10.2.2之地理编码服务发布
1.地理编码工具(Geocoding Tools)locator制作 打开arcCatalog,找到工具箱ArcToolbox中的Geocoding Tools---Create Addres ...
- ArcGIS 的 Oracle 数据库的要求
[ArcGIS必打补丁]ArcGIS 10.2.2 for Desktop连接Oracle(2014年10月发布)数据库崩溃的问题 http://blog.csdn.net/linghe301/art ...
- SharePoint 2013 图文开发系列之自定义字段
SharePoint使用的优势,就在于开箱即用.快速搭建,SharePoint自身为我们提供了很多字段类型,已经很丰富了.但是,在实际应用中,我们还需要一些功能特殊的字段,下面,我们简单介绍下字段的开 ...
- Sharepoint学习笔记—习题系列--70-576习题解析 -(Q105-Q108)
Question 105 You are designing a SharePoint 2010 application that contains a single list named Us ...
- APP上架证书无效:解决
转发:http://www.cnblogs.com/pruple/p/5523767.html 转发:http://blog.csdn.net/sunnyboy9/article/details/50 ...
- 学习tensorflow之mac上安装tensorflow
背景 听说谷歌的第二代机器学习的框架tensorflow开源了,我也心血来潮去探探大牛的产品.怎奈安装就折腾了一天,现在整理出来备忘. tensorflow官方网站给出的安装步骤很简单: # Only ...
- [转]PaaS平台分类
本文转自阿朱说 大家发现没,自从我们上升到有规模的互联网架构后,咱们中国的技能能力就跟不上了,只能采取国际业界顶级大公司开源出来的而且已经经受住大规模实际应用考验的组件来搭架构,因而咱们近几年大规模网 ...
- Linux查看设置系统时区
关于时区的概念,其实初中地理课已经涉及,很多人都多少了解一些,可能只是细节搞不太清楚.为什么会将地球分为不同时区呢?因为地球总是自西向东自转,东边总比西边先看到太阳,东边的时间也总比西边的早.东边时刻 ...
- send+recv注意事项
[TOC] send 函数原型 ssize_t send( SOCKET s, const char *buf, size_t len, int flags ) 注意事项 待发送数据长度data_le ...
- explicit抑制隐型转换
本文出自 http://www.cnblogs.com/cutepig/ 按照默认规定,只有一个参数的构造函数也定义了一个隐式转换,将该构造函数对应数据类型的数据转换为该类对象,如下面所示: clas ...