页面请求步骤:

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认证的更多相关文章

  1. asp.net权限认证:Forms认证

    asp.net权限认证系列 asp.net权限认证:Forms认证 asp.net权限认证:HTTP基本认证(http basic) asp.net权限认证:Windows认证 asp.net权限认证 ...

  2. 在asp.net WebAPI 中 使用Forms认证和ModelValidata(模型验证)

    一.Forms认证 1.在webapi项目中启用Forms认证 Why:为什么要在WebAPI中使用Forms认证?因为其它项目使用的是Forms认证. What:什么是Forms认证?它在WebAP ...

  3. django的forms认证组件

    django的forms认证组件 每个网站的注册界面都需要有相应的"认证"功能,比如说认证注册页面的用户名是否已被注册,二次输入的密码是否一致以及认证用户输入的用户名.邮箱.手机号 ...

  4. ASP.NET Forms 认证流程

    ASP.NET Forms 认证 Forms认证基础 HTTP是无状态的协议,也就是说用户的每次请求对服务器来说都是一次全新的请求,服务器不能识别这个请求是哪个用户发送的. 那服务器如何去判断一个用户 ...

  5. asp.net forms认证

    工作中遇到的asp.net项目使用forms认证.以前虽然用过,但其原理并不了解,现在甚至对什么是form认证也完全不知道了.对一样东西如果不清楚其原理,不知其所以然,那么死记硬背是无济于事的. as ...

  6. [mvc] 简单的forms认证

    1.在web.config的system.web节点增加authentication节点,定义如下: <system.web> <compilation debug="tr ...

  7. Asp.net forms认证注意事项

    1.N台服务器配置文件的相关配置要一致 <authentication mode="Forms"> <forms timeout="3600" ...

  8. IE11无法支持Forms认证,,,也就是无法保存COOKIE

    <authentication mode="Forms"> <forms name="xxxx" loginUrl="login.a ...

  9. 解决由AJAX请求时forms认证实效的重新认证问题

    前言: 当用AJAX请求一个资源时,服务器检查到认证过期,会重新返回302,通过HTTP抓包,是看到请求了登录页面的,但是JS是不会进行跳转到登录页面. 使用环境: ASP.NET MVC 4 JQU ...

随机推荐

  1. 洗礼灵魂,修炼python(23)--自定义函数(4)—闭包进阶问题—>报错UnboundLocalError: local variable 'x' referenced before assignment

    闭包(lexical closure) 什么是闭包前面已经说过了,但是由于遗留问题,所以单独作为一个章节详解讲解下 不多说,看例子: def funx(x): def funy(y): return ...

  2. linux上文件内容去重的问题uniq/awk

    1.uniq:只会对相邻的行进行判断是否重复,不能全文本进行搜索是否重复,所以往往跟sort结合使用. 例子1: [root@aaa01 ~]# cat a.txt 12 34 56 12 [root ...

  3. 成功清除 windows2008 内部版本7601 字眼

    cmd—>bcdedit -set testsigning off重启电脑就好了

  4. 高通非adsp 架构下的sensor的bug调试

    高通 sensor 从native到HAL 高通HAL层之Sensor HAL 高通HAL层之bmp18x.cpp 问题现象: 当休眠后,再次打开preesure sensor的时候,会出现隔一段时候 ...

  5. windows 实用技巧

    以下内容版权归原作者所有!!!如果侵权,立即删除. 1.系统激活:https://mp.weixin.qq.com/s/Kl_iEeSSxSprblfSRZ6yEQ 2.百度云下载:https://w ...

  6. Django学习---py3下的富文本编辑器的使用

    背景说明: Ueditor HTML编辑器是百度开源的HTML编辑器,但是在Python3下调用报错,找不到widgets模块,经查发现,DjangoUeditor是基于Python 2.7的,对Py ...

  7. JQuery 获取多个select标签option的text内容

    根据option的id属性,修改text值 $("#sel_div .select_class option[id='-选择省-']").text(data.province).a ...

  8. Python3编写网络爬虫07-基本解析库pyquery的使用

    三.pyquery 简介:同样是一个强大的网页解析工具 它提供了和jQuery类似的语法来解析HTML文档,支持CSS选择器,使用非常方便 安装: pip install pyquery 验证: im ...

  9. [Jenkins] 如何修改jenkins上的环境变量

    现象 当本地的环境变量发生变化时,在jenkins 构建时里面访问的环境变量仍是之前旧的(未更新的)导致构建出现错误,比如我以我所遇到的问题进行简单写下,下面例子中我是涉及到修改 PYTHONPATH ...

  10. easyui的datebox控件如何只要年月不要日谢谢知道的说一下

    例子2015-01 格式easyui-datebox 加上 data-options="formatter:myformatter,parser:myparser"function ...