Asp.Net MVC 自定义登录过滤器
1、新建类BaseController用于统一所有控制器继承扩展,方便扩展登录等过滤器。示例如下:
using CloudWave.JustBeHere.JBH_H5.Controllers.Attribute;
using CloudWave.JustBeHere.JBH_H5.Controllers.Authorization;
using CloudWave.JustBeHere.JBH_H5.Models.User;
using CloudWave.JustBeHere.Web;
using Jil;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using static CloudWave.JustBeHere.JBH_H5.Models.Commn.BaseModel; namespace CloudWave.JustBeHere.JBH_H5.Controllers
{
[Auth]
[ResultFilter]
#if (!DEBUG)
[Error]
#endif
public class BaseController : Controller
{ public Authentication authentication = Authentication.Instance;
public bool IsLogin
{
get
{
//return true;
return authentication.IsLogin;
}
}
public LoginResult Operator
{
get
{
return authentication.CurrentUser;
}
}
private string _hostName; /// <summary>
/// 获取请求的域名
/// </summary>
public string HostName
{
get
{
if (string.IsNullOrEmpty(_hostName))
{
var url = Request.Url.ToString();
// http(s)?://([\w-]+\.{0,1})+\:{0,1}[0-9]{0,1}[\w-]?
var reg = new Regex(@"//([\w-]+\.{0,1})+\:{0,1}[0-9]{0,1}[\w-]+/?");
var result = reg.Match(url, ).Value;
_hostName = result;
}
return _hostName;
}
} private string _hostFullName; /// <summary>
/// 获取请求的域名全称(含请求协议)
/// </summary>
public string HostFullName
{
get
{
if (string.IsNullOrEmpty(_hostFullName))
{
var url = Request.Url.ToString();
// http(s)?://([\w-]+\.{0,1})+\:{0,1}[0-9]{0,1}[\w-]?
var reg = new Regex(@"http(s)?://([\w-]+\.{0,1})+\:{0,1}[0-9]{0,1}[\w-]+/?");
var result = reg.Match(url, ).Value;
_hostFullName = result;
}
return _hostFullName;
}
} /// <summary>
/// 是否为手机端访问
/// </summary>
public bool IsMobile
{
get
{
var uAgent = Request.ServerVariables["HTTP_USER_AGENT"];
var b = new Regex(@"android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline);
var v = new Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-", RegexOptions.IgnoreCase | RegexOptions.Multiline);
return b.IsMatch(uAgent) || v.IsMatch(uAgent.Substring(, ));
}
}
}
}
2、新建类Authentication用于管理Session、Cookie等信息。示例如下:
using CloudWave.JustBeHere.JBH_H5.Models.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security; namespace CloudWave.JustBeHere.JBH_H5.Controllers.Authorization
{
public class Authentication
{
public const string UserSessionKey = "UserInfo"; private Authentication()
{
} public static Authentication Instance
{
get
{
return new Authentication();
}
} /// <summary>
/// 写入验证信息
/// </summary>
/// <param name="uInfo"></param>
/// <param name="isPersistent">是否保存</param>
public void SetAuth(LoginResult uInfo, bool isPersistent)
{
string token = uInfo.Id + "|" + uInfo.Token;
//将用户ID和角色写入Cookie
FormsAuthentication.SetAuthCookie(token, isPersistent, FormsAuthentication.FormsCookiePath);
HttpCookie authCookie = FormsAuthentication.GetAuthCookie(token, isPersistent);
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
//FormsAuthentication.RedirectFromLoginPage(ticket.Name, true); FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, DateTime.Now.AddDays(), ticket.IsPersistent, "");
authCookie.Value = FormsAuthentication.Encrypt(newTicket);
HttpContext.Current.Response.AddHeader("P3P", "CP=CAO PSA OUR");//解决ie js跨域调用
HttpContext.Current.Response.Cookies.Add(authCookie);
SetSession(uInfo);
} /// <summary>
///保存用户状态
/// </summary>
/// <param name="uInfo"></param>
public void SetSession(LoginResult uInfo)
{
HttpContext.Current.Session[UserSessionKey] = uInfo;
}
/// <summary>
///保存用户状态
/// </summary>
/// <param name="uid"></param>
public void SetSession(int uid)
{
bool setFlag = false;
if (HttpContext.Current.Session == null)
{
throw new ArgumentNullException("SessionState Failed");
}
if (HttpContext.Current.Session[UserSessionKey] == null)
{
setFlag = true;
}
else
{
//得到用户信息
LoginResult sulr = HttpContext.Current.Session[UserSessionKey] as LoginResult;
if (sulr.Id != uid) setFlag = true;
}
if (setFlag)
{
try
{
//var u = GetUserInfo();
//if (u != null)
//{
// HttpContext.Current.Session[UserSessionKey] = u;
//}
new RedirectToRouteResult("default", new System.Web.Routing.RouteValueDictionary(new { action = "Index", controller = "Home" }));
}
catch { }
}
}
private LoginResult GetUserInfo()
{
var client = new Api(WebCommon.ApiUrl, WebCommon.ActiveUser, WebCommon.ApiToken);
LoginResult slr = new LoginResult();
client.Request.Header.Cmd = "api/staffuser/getstaffuserinfo";
slr = client.ExecutePost<LoginResult>();
if (client.Response.Header.statusCode == )
{
return slr;
}
else { return null; }
} /// <summary>
/// 登出
/// </summary>
public void SignOut()
{
FormsAuthentication.SignOut();
HttpContext.Current.Session.Clear();
} public bool IsLogin
{
get
{
return HttpContext.Current != null ? HttpContext.Current.Request.IsAuthenticated : false;
}
} /// <summary>
/// 当前用户信息
/// </summary>
public LoginResult CurrentUser
{
get
{
if (!IsLogin)
{
return null;
}
int uid;
if (int.TryParse(HttpContext.Current.User.Identity.Name.Split('|')[], out uid))
{
if (HttpContext.Current.Session[UserSessionKey] == null)
{
SetSession(uid);
}
return HttpContext.Current.Session[UserSessionKey] as LoginResult;
}
return null;
}
} //public void RefreshInfo()
//{
// UsersExtensionInfo u = UsersService.GetById(HttpContext.Current.User.Identity.Name);
// u.ImName = UsersService.GetImName(u.TTUserId);
// HttpContext.Current.Session[UserSessionKey] = UserInfoDec(u);
//}
}
}
3、新建类AuthAttribute,继承AuthorizeAttribute类。示例如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace CloudWave.JustBeHere.JBH_H5.Controllers.Attribute
{
/// <summary>
/// 登录过滤器
/// </summary>
public class AuthAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
var controller = filterContext.Controller as BaseController;
if (controller.IsLogin)
{
filterContext.Controller.ViewBag.UserInfo = controller.Operator?.Id;
// filterContext.Controller.ViewBag.PartnerName = controller.Operator?.PartnerName;
}
else
{
filterContext.Controller.ViewBag.UserInfo = "";
// filterContext.Controller.ViewBag.PartnerName = "";
}
if (!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) && !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
{
if (!controller.IsLogin)
{
//if (filterContext.HttpContext.Request.IsAjaxRequest())
//{
// filterContext.Result = new JsonResult
// {
// Data = "needlogin",
// JsonRequestBehavior = JsonRequestBehavior.AllowGet
// };
//}
//else
//{
// string reutrnUrl = filterContext.RequestContext.HttpContext.Request.RawUrl;
// filterContext.Result = new RedirectToRouteResult("default", new System.Web.Routing.RouteValueDictionary(new { action = "index", controller = "Home", returnUrl = reutrnUrl })); //}
string reutrnUrl = filterContext.RequestContext.HttpContext.Request.RawUrl;
filterContext.Result = new RedirectToRouteResult("default", new System.Web.Routing.RouteValueDictionary(new { action = "index", controller = "Home", returnUrl = reutrnUrl }));
}
}
//if (!AuthorizeCore(filterContext.HttpContext)) {
// HandleUnauthorizedRequest(filterContext);
//} else {
// filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
//}
}
}
}
4、在Web.config的节点system.web下新增如下节点配置:
<authentication mode="Forms">
<forms loginUrl="/Home/Index" timeout="43200"></forms>
</authentication>
5、返回信息过滤器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security; namespace CloudWave.JustBeHere.JBH_H5.Controllers.Attribute
{ /// <summary>
/// 请求返回结果过滤器
/// </summary>
public class ResultFilterAttribute : ActionFilterAttribute
{ public override void OnResultExecuting(ResultExecutingContext filterContext)
{
if (filterContext.Result is ViewResult)
{
var controller = (BaseController)filterContext.Controller;
FormsAuthentication.SignOut();
HttpContext.Current.Session.Clear();
}
base.OnResultExecuting(filterContext);
}
}
}
Asp.Net MVC 自定义登录过滤器的更多相关文章
- asp.net mvc 自定义全局过滤器 验证用户是否登录
一般具有用户模块的系统都需要对用户是否登录进行验证,如果用户登录了就可以继续操作,否则退回用户的登录页面 对于这样的需求我们可以通过自定义一个独立的方法来完成验证的操作,但是这样代码的重复率就大大提高 ...
- ASP.NET MVC自定义验证Authorize Attribute(包含cookie helper)
前几天Insus.NET有在数据库实现过对某一字段进行加密码与解密<使用EncryptByPassPhrase和DecryptByPassPhrase对MS SQLServer某一字段时行加密和 ...
- Asp.Net MVC<五>:过滤器
ControllerActionInvoker在执行过程中除了利用ActionDescriptor完成对目标Action方法本身的执行外,还会执行相关过滤器(Filter).过滤器采用AOP的设计,它 ...
- ASP.NET MVC 自定义Razor视图WorkContext
概述 1.在ASP.NET MVC项目开发的过程中,我们经常需要在cshtml的视图层输出一些公用信息 比如:页面Title.服务器日期时间.页面关键字.关键字描述.系统版本号.资源版本号等 2.普通 ...
- asp.net mvc 自定义pager封装与优化
asp.net mvc 自定义pager封装与优化 Intro 之前做了一个通用的分页组件,但是有些不足,从翻页事件和分页样式都融合在后台代码中,到翻页事件可以自定义,再到翻页和样式都和代码分离, 自 ...
- ASP.NET MVC学习之过滤器篇(2)
下面我们继续之前的ASP.NET MVC学习之过滤器篇(1)进行学习. 3.动作过滤器 顾名思义,这个过滤器就是在动作方法调用前与调用后响应的.我们可以在调用前更改实际调用的动作,也可以在动作调用完成 ...
- ASP.NET MVC 自定义路由中几个需要注意的小细节
本文主要记录在ASP.NET MVC自定义路由时,一个需要注意的参数设置小细节. 举例来说,就是在访问 http://localhost/Home/About/arg1/arg2/arg3 这样的自定 ...
- Asp.net Mvc 自定义Session (二)
在 Asp.net Mvc 自定义Session (一)中我们把数据缓存工具类写好了,今天在我们在这篇把 剩下的自定义Session写完 首先还请大家跟着我的思路一步步的来实现,既然我们要自定义Ses ...
- Asp.net mvc 自定义全局的错误事件HandleErrorAttribute无效
Asp.net mvc 自定义全局的错误事件HandleErrorAttribute,结果无效, 原因: 1.没有在RegisterGlobalFilters 里面添加或者你要的位置添加. 2.你把这 ...
随机推荐
- Python Pygame (3) 界面显示
显示模式: 之前使display模块的set_mode()的方法用来指定界面的大小,并返回一个Surface对象. set_mode()的原型如下: display.set_mode(resoluti ...
- 20181120-8 Beta阶段第2周/共2周 Scrum立会报告+燃尽图 06
此作业要求参见:https://edu.cnblogs.com/campus/nenu/2018fall/homework/2414 版本控制地址 [https://git.coding.net ...
- 王者荣耀交流协会第一次Scrum立会
工作照片: scrum master:高远博 时间跨度;2017/10/13 6:04-6:34 地点:一食堂二楼两张桌子旁 立会内容; 昨天的成绩;昨天商议了今天的开会的时间.地点 今天的计划;讨论 ...
- 利用p4实现ipv6转发实验
写在前面 只是作为一个入门p4的实验尝试,借用了一些即成的运行代码. p4代码 /**p4_16,v1_model**/ #include<core.p4> #include<v1m ...
- lintcode-511-交换链表当中两个节点
511-交换链表当中两个节点 给你一个链表以及两个权值v1和v2,交换链表中权值为v1和v2的这两个节点.保证链表中节点权值各不相同,如果没有找到对应节点,那么什么也不用做. 注意事项 你需要交换两个 ...
- Spring管理过滤器:org.springframework.web.filter.DelegatingFilterProxy
配置web.xml <filter> <filter-name>springSecurityFilterChain</filter-name> ...
- Linux安装weblogic
一.软件安装 1. 安装前的准备工作 1.1 首先请确认您要安装的WebLogic版本所在的平台已通过了BEA的认证,完整的认证平台列表请参考 http://e-docs.bea.com/wls/ce ...
- 用iptables做代理
出于安全考虑,Linux系统默认是禁止数据包转发的.配置Linux系统的ip转发功能,打开系统转发功能:echo "1" > /proc/sys/net/ipv4/ip_fo ...
- Fn+F1-F12,避免使用FN+
用惯了win8.1,再用win10 很不习惯使用FN+F1-F12 如果要避免使用FN+:使用[FN+ESC]
- RAD Studio 10.3 Rio (BCB & Dephi) 发布啦
期盼已久的RAD Studio 10.3 Rio 终于发布了: 下载链接:http://altd.embarcadero.com/download/radstudio/10.3/delphicbui ...