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 ...
随机推荐
- python第八十四天---十五周作业
后台管理页面: <!DOCTYPE html> <html lang="en"> <head> <meta charset="U ...
- 怎样让引用类库的类在HelpPage上显示Description
最近在做 web api 开发的时候遇到这样的问题,即 HelpPage 里只能显示 api 控制器上的注释,对于那些引用了外部类库的类(比如POST提交需要用到的类),就无法显示它们的备注, ...
- Dota 2 中安装包的作用
在玩data 2 的时候有很多其他安装包的下载,那这些有啥用呢? Reborn是Dota2的重生客户端,也就是主客户端. Opengl是显卡优化的,应该是微软的一个标准,有助于提高游戏的 FPS. V ...
- [SequenceFile_3] MapFile
0. 说明 MapFile 介绍 && 测试 1. 介绍 对 MapFile 的介绍如下: MapFile 是带有索引的 SequenceFile MapFile 是排序的 Seque ...
- JAVA中实现单例(Singleton)模式的八种方式
单例模式 单例模式,是一种常用的软件设计模式.在它的核心结构中只包含一个被称为单例的特殊类.通过单例模式可以保证系统中,应用该模式的类一个类只有一个实例.即一个类只有一个对象实例. 基本的实现思路 单 ...
- js 提交表单添加csrf
function post(path, shipmentMap, method) { method = method || "post"; // Set method to pos ...
- Java没有头文件的原因
http://bbs.csdn.net/topics/100134244 C/C++ 之所以需要头文件(.h),有两个用处,一个是在开发编译的时候,在各个编译单元(Compile Unit)之间共享同 ...
- 在centos7上修改docker加速镜像为阿里云
使用docker pull,命令下载镜像太慢了,默认是从国外的,本文记录下如何配置国内阿里云竞相加速方式. 登录https://cr.console.aliyun.com,如下, 阿里云会为每个用户提 ...
- 【转】Kaggle注册问题-验证码和手机短信
注册和登录Kaggle时验证码无法显示问题 参考:https://blog.csdn.net/zhuisaozhang1292/article/details/81529981 应用FQ软件需要时时关 ...
- MATLAB——sigmoid传递函数
一.log——sigmoid函数 二.tan——sigmoid函数