页面请求步骤:

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第九天----今天来晚了!

    作业 1. HAproxy配置文件操作1. 根据用户输入输出对应的backend下的server信息2. 可添加backend 和sever信息3. 可修改backend 和sever信息4. 可删除 ...

  2. Xamarin是无懈可击还是鸡肋?浅谈对Xamarin的学习

    微软宣布跨平台已经有几个年头,当C#代码可以在其他平台运行时,我相信对于每个热爱.net的程序猿还是十分欣慰的,最近工作需要在一直研究和学习.net的跨平台开发Xamarin,网上对其优点总结也是一大 ...

  3. pycharm的安装和使用小技巧

    一,pycharm 1,在官网下载pycharm,版本选5.0,一定要下载专业版. 2,注册方法:注册时选择 license server,填入:http://idea.qinxi1992.cn,然后 ...

  4. NFS服务搭建与配置

    启动NFS SERVER之前,首先要启动RPC服务(CentOS5.8下为portmap服务,CentOS6.6下为rpcbind服务,下同),否则NFS SERVER就无法向RPC服务注册了.另外, ...

  5. DFS普及组常用模板简单整理

    一些普及组会用到的DFS模板,其他的DFS我感觉普及组不会用到所以暂且搁着,等之后有时间了再细写w (至于我为什么最近不写TG相关只写最基础的PJ的内容,请戳这里了解) dfs各种模板big集合 1. ...

  6. Opaque data type--不透明类型

    Opaque:对使用者来说,类型结构和机制明晰即为transparent,否则为Opaque In computer science, an opaque data type is a data ty ...

  7. 转 一个web项目web.xml的配置中<context-param>配置作用

    一个web项目web.xml的配置中<context-param>配置作用   <context-param>的作用:web.xml的配置中<context-param& ...

  8. 数据库连性池性能测试(hikariCP,druid,tomcat-jdbc,dbcp,c3p0)

    文章转自  https://www.tuicool.com/articles/qayayiM 摘要: 本文主要是对这hikariCP,druid,tomcat-jdbc,dbcp,c3p0几种连接池的 ...

  9. 谈谈maven多模块

    记得在校的时候,通常用的比较多是动态web工程,动态web工程导入最多就是jar包,这些jar包需要自己手动复制粘贴放入lib目录下,然后build path,有的IDE会自动build path有的 ...

  10. 在Qt项目中如何添加一个已有的项目作为子项目

    新建一个子目录项目(具体方法参见<类似Visual Studio一样,使用Qt Creator管理多个项目,创建子项目>),然后需要添加的项目移动到该子目录项目目录下,再在其pro文件中添 ...