Authorize的Forms认证
页面请求步骤:
1.登录地址: http://localhost:4441/SysLogin/AdminLogin
2.登陆成功地址:http://localhost:4441/Frame/MainFrame
3.点击页面退出,清除Session/Cookie跳转到登录页面
4.Url输入登录成功的地址界面自动验证授权进入:http://localhost:4441/SysLogin/AdminLogin?ReturnUrl=%2fFrame%2fMainFrame
代码实现步骤:
1.登录页面:SysLogin/AdminLogin,不继承BaseController
[HttpPost]
[OperateLoggerFilter(IsRecordLog = false, ConName = "系统登录", ActName = "用户登录")]
public ActionResult LoginAuthentica(string Account, string Pwd)
{
try
{
var Result = AdminServiceDb.GetEntityByWhere(it => it.Account == Account);
if (Result == null)
{
return Json(new { result = false, msg = "用户不存在" });
}
else
{
Pwd = StringHelper.MD5(Pwd);
if (Result.PassWord != Pwd)
{
return Json(new { result = false, msg = "密码错误" });
}
DateTime overdueDate;
string value = Result.ID.ToString();
value = Encrypt.Encrypto(value);
overdueDate = DateTime.Now.AddMinutes();
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
,
Guid.NewGuid().ToString(),
DateTime.Now,
overdueDate,
false,
value
);
FormsAuthenticationTicket t = new FormsAuthenticationTicket(, "", DateTime.Now, overdueDate, false, value);
string hashTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
Response.Cookies.Add(cookie);
string url = Url.Action("MainFrame", "Frame");
return Json(new { result = true, msg = url });
}
}
catch (Exception ex)
{
LogHelper.Error(this, ex);
return Json(new { result = false, msg = "异常:登录失败" });
}
}
登录方法
2.登录成功后:Frame/MainFrame,继承BaseController
[System.Web.Mvc.Authorize]//引用授权 public class FrameController : BaseController
{
......
3.WebConfig配置:
<authentication mode="Forms">
<forms loginUrl="~/SysLogin/AdminLogin" timeout="" />
</authentication>
4.登录Controller的特性页面:
public class OperateLoggerFilter : FilterAttribute, IActionFilter
{ private LogService logServiceDb = new LogService(); /// <summary>
/// 是否记录日志,默认为不记录
/// </summary>
public bool IsRecordLog = false; /// <summary>
/// 控制器中文名
/// </summary>
public string ConName = string.Empty; /// <summary>
/// 方法中文名
/// </summary>
public string ActName = string.Empty; /// <summary>
/// 是否为form提交,若是则设置为true,否则报错,默认为false
/// </summary>
public bool IsFormPost = false; /// <summary>
/// 如果是form提交(IsFormPost为true),则需要设置此字段,此字段代表请求方法的参数类型集合
/// </summary>
public Type[] Entitys = null; /// <summary>
/// Action执行后
/// </summary>
void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
{ if (!IsRecordLog)
return; //var result = string.Empty;
if (filterContext.Result is ViewResult)
return;
//result = ((System.Web.Mvc.JsonResult)filterContext.Result).Data.ToString(); string controller = filterContext.Controller.ToString(); string action = filterContext.ActionDescriptor.ActionName; Type type = Type.GetType(controller);
ParameterInfo[] parasInfo = null;
if (!IsFormPost)
parasInfo = type.GetMethod(action).GetParameters();
else
parasInfo = type.GetMethod(action, Entitys).GetParameters(); if (parasInfo == null || parasInfo.Length == )
return; StringBuilder content = new StringBuilder();
if (!IsFormPost)
foreach (var item in parasInfo)
{
content.Append(item.Name);
content.Append(":");
if (filterContext.HttpContext.Request[item.Name] == null)
content.Append("null");
else
content.Append(filterContext.HttpContext.Request[item.Name].ToString());
content.Append(";");
}
else
foreach (var item in parasInfo)
{
PropertyInfo[] fileds = Entitys[].GetProperties();
foreach (var f in fileds)
{
if (filterContext.HttpContext.Request[f.Name] == null)
continue;
content.Append(f.Name);
content.Append(":");
content.Append(filterContext.HttpContext.Request[f.Name].ToString());
content.Append(";");
} } var user = filterContext.HttpContext.User.Identity.Name; //-------------
string cookieName = FormsAuthentication.FormsCookieName;//从验证票据获取Cookie的名字。
//取得Cookie.
HttpCookie authCookie = filterContext.HttpContext.Request.Cookies[cookieName];
if (null == authCookie)
return;
FormsAuthenticationTicket authTicket = null;
//获取验证票据。
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket == null)
return; //验证票据的UserData中存放的是用户信息。
//UserData本来存放用户自定义信息。
string userData = authTicket.UserData;
string userId = Foc_Sys_Public.Encrypt.Decrypto(userData);
FormsIdentity id = new FormsIdentity(authTicket);
//把生成的验证票信息和角色信息赋给当前用户. Guid uid;
if (Guid.TryParse(userId, out uid))
{
var model = new LogEntity
{
ID = Guid.NewGuid(),
UserID = uid,
Controller = ConName.Trim() == string.Empty ? controller : ConName.Trim(),
Action = ActName.Trim() == string.Empty ? action : ActName.Trim(),
Content = content.ToString().Length > ? content.ToString().Substring(, ) : content.ToString(),
//OperateResult = result.Contains("True") ? true : false,
IsDel = false,
CreatTime = DateTime.Now,
}; logServiceDb.AddEntity(model);
}
} /// <summary>
/// Action执行前
/// </summary>
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{ }
}
5.BaseController页面:
/// <summary>
/// 基础控制器 所有控制器必须继承
/// </summary>
[System.Web.Mvc.Authorize]
public class BaseController : Controller
{ protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
string IsAjax = Request.Headers["X-Requested-With"];
if (string.IsNullOrEmpty(IsAjax))
{
if (!IsCheckJJurisdicti(filterContext))
{
filterContext.Result = Redirect(Url.Action("Page503", "Frame"));
}
}
base.OnActionExecuting(filterContext);
} protected override void OnException(ExceptionContext filterContext)
{
if (!filterContext.ExceptionHandled)
{
filterContext.ExceptionHandled = true;
LogHelper.Error(filterContext.Controller, filterContext.Exception);
}
filterContext.Result = Redirect(Url.Action("Page503", "Frame"));
base.OnException(filterContext);
}
}
BaseController页面
注意:
<system.webServer>
<!--<modules>
<remove name="FormsAuthentication" />
</modules>-->
</system.webServer> 配置文件要注释掉这句。不然进入会404错误。
Authorize的Forms认证的更多相关文章
- asp.net权限认证:Forms认证
asp.net权限认证系列 asp.net权限认证:Forms认证 asp.net权限认证:HTTP基本认证(http basic) asp.net权限认证:Windows认证 asp.net权限认证 ...
- 在asp.net WebAPI 中 使用Forms认证和ModelValidata(模型验证)
一.Forms认证 1.在webapi项目中启用Forms认证 Why:为什么要在WebAPI中使用Forms认证?因为其它项目使用的是Forms认证. What:什么是Forms认证?它在WebAP ...
- django的forms认证组件
django的forms认证组件 每个网站的注册界面都需要有相应的"认证"功能,比如说认证注册页面的用户名是否已被注册,二次输入的密码是否一致以及认证用户输入的用户名.邮箱.手机号 ...
- ASP.NET Forms 认证流程
ASP.NET Forms 认证 Forms认证基础 HTTP是无状态的协议,也就是说用户的每次请求对服务器来说都是一次全新的请求,服务器不能识别这个请求是哪个用户发送的. 那服务器如何去判断一个用户 ...
- asp.net forms认证
工作中遇到的asp.net项目使用forms认证.以前虽然用过,但其原理并不了解,现在甚至对什么是form认证也完全不知道了.对一样东西如果不清楚其原理,不知其所以然,那么死记硬背是无济于事的. as ...
- [mvc] 简单的forms认证
1.在web.config的system.web节点增加authentication节点,定义如下: <system.web> <compilation debug="tr ...
- Asp.net forms认证注意事项
1.N台服务器配置文件的相关配置要一致 <authentication mode="Forms"> <forms timeout="3600" ...
- IE11无法支持Forms认证,,,也就是无法保存COOKIE
<authentication mode="Forms"> <forms name="xxxx" loginUrl="login.a ...
- 解决由AJAX请求时forms认证实效的重新认证问题
前言: 当用AJAX请求一个资源时,服务器检查到认证过期,会重新返回302,通过HTTP抓包,是看到请求了登录页面的,但是JS是不会进行跳转到登录页面. 使用环境: ASP.NET MVC 4 JQU ...
随机推荐
- WCF服务端开发和客户端引用小结
1.服务端开发 1.1 WCF服务创建方式 创建一个WCF服务,总是会创建一个服务接口和一个服务接口实现.通常根据服务宿主的不同,有两种创建方式. (1)创建WCF应用程序 通过创建WCF服务应用程序 ...
- Linux 装机必备工具
linux 装机必备工具:安装这些基本能满足日常需求. #!/usr/bin/env sh echo "Env" # vim # tmux # ssh ...
- Centos7系统如何不重启系统识别新添加的硬盘?
今天在系统开机后插入三块硬盘,结果没有一块硬盘被系统识别到.后来找到了方法. echo "- - -" > /sys/class/scsi_host/host0/scan 上 ...
- MySQL面试题之如何优化一条有问题的SQL语句?
如何优化一条有问题的sql语句? 针对sql语句的优化.我们可以从如下几个角度去分析 回归到表的设计层面,数据类型选择是否合理 大表碎片的整理是否完善 表的统计信息,是不是准确的 审查表的执行计划,判 ...
- Beta冲刺(4/5)(麻瓜制造者)
今日已完成 邓弘立:完成了商品管理(下架)和搜索功能 符天愉:完成了后台管理员界面的登录和其他视图的载入 江郑:昨天来决定跨域执行请求,后台参考一些意见以后,操作起来没有那么容易实现,和队友交流以后本 ...
- windows下基于IIS配置ssl证书
我这边用的是阿里云的免费证书,下面展示一下操作步骤. 首先登陆阿里云,搜索ssl证书进入ssl证书控制台.点击购买 然后选择免费版,配置如下: 选择立即购买,购买成功后回到ssl控制台即可查看证书.然 ...
- M100 X3云台安装
http://bbs.dji.com/thread-38587-1-1.html
- Spring Security 用户认证原理分析
本文基于 spring-security-core-5.1.1 和 tomcat-embed-core-9.0.12. 核心原理 用户通过 username 和 password 登录时,后端会经过一 ...
- Spring Security 重定向原理分析
本文基于 spring-security-core-5.1.1 和 tomcat-embed-core-9.0.12. 一个用户访问使用表单认证的 Web 应用时,后端的处理流程大致如下: 1.用户访 ...
- Python基础(2)——列表、字典、数据运算
1.列表 #创建列表 name_list = ['alex', 'seven', 'eric'] #或 name_list = list(['alex', 'seven', 'eric']) #访问列 ...