ASP.NET MVC Cookie 身份验证
1 创建一个ASP.NET MVC 项目
添加一个 AccountController 类。
public class AccountController : Controller
{
[HttpGet]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
[HttpPost]
public ActionResult Login(string userName, string password,string returnUrl)
{
if (CheckLogin(userName, password))
{
//加入票据 //保存身份信息
AccountModel ModelUser = new AccountModel() { UserName = userName, Password = password };
string UserData = JsonConvert.SerializeObject(ModelUser);//序列化用户实体
FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddHours(1), false, UserData);
HttpCookie Cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(Ticket));//加密身份信息,保存至Cookie
Response.Cookies.Add(Cookie); if (string.IsNullOrEmpty(returnUrl))
{
return Redirect("~/Home/Index");
}
else
{
return Redirect(returnUrl);
} }
else
{
return View("Login", new ResultModel<string>() { Code = 1, Message = "用户名或密码错误" });
} }
public ActionResult Logout()
{
FormsAuthentication.SignOut();
return RedirectToAction("Login");
} private bool CheckLogin(string userName, string password)
{
return MvcApplication.DBList.Any(n => n.UserName == userName && n.Password == password);
} }
2 添加一个 自定义attribute ,用来过滤身份登录
public class CheckLoginAttribute :ActionFilterAttribute
{ public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//如果存在身份信息
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
ContentResult Content = new ContentResult();
string url = string.Format("{0}?returnUrl={1}", FormsAuthentication.LoginUrl, filterContext.HttpContext.Request.RawUrl);
Content.Content = string.Format("<script type='text/javascript'>alert('请先登录!');window.location.href='{0}';</script>", url);
filterContext.Result = Content;
}
//else
//{
// string[] Role = CheckLogin.Instance.GetUser().Roles.Split(',');//获取所有角色
// if (!Role.Contains(Code))//验证权限
// {
// //验证不通过
// ContentResult Content = new ContentResult();
// Content.Content = "<script type='text/javascript'>alert('权限验证不通过!');history.go(-1);</script>";
// filterContext.Result = Content;
// }
//}
}
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
3 设置 web.config , 注意 一定要添加 mode=“Forms”
<system.web>
....
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" name=".iamshop" ></forms>
</authentication>
...
</system.web>
4 需要添加权限验证的地方: 标记一个[CheckLogin] 属性
[CheckLogin]
public ActionResult Index()
{
//获取登录信息
ViewBag.UserName = User.Identity.Name;
//获取对象
// FormsIdentity ticket = (FormsIdentity)User.Identity;
HttpCookie authCookie = HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];//获取cookie
FormsAuthenticationTicket Ticket = FormsAuthentication.Decrypt(authCookie.Value);//解密
// AccountModel account = (AccountModel)JsonConvert.DeserializeObject(Ticket.UserData);//反序列化
AccountModel account= JsonConvert.DeserializeObject<AccountModel>(Ticket.UserData);
ViewBag.AccountName = account.UserName;
ViewBag.Password = account.Password; return View();
}
网上身份验证代码很多,参考后做的一个笔记,需要使用时,根据情况修改使用。
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
ASP.NET MVC Cookie 身份验证的更多相关文章
- asp.net mvc 自定义身份验证
1.定义身份实体对象 /// <summary> /// 网站用户实体对象 /// </summary> public class DDTPrincipal : IPrinci ...
- asp.net mvc 自定义身份验证 2
控制成员角色 [Authorize(Rroles="Administator,SuperAdmin")] public class StoreManagerController:C ...
- 使用JWT的ASP.NET CORE令牌身份验证和授权(无Cookie)——第1部分
原文:使用JWT的ASP.NET CORE令牌身份验证和授权(无Cookie)--第1部分 原文链接:https://www.codeproject.com/Articles/5160941/ASP- ...
- 采用Asp.Net的Forms身份验证时,持久Cookie的过期时间会自动扩展
原文:http://www.cnblogs.com/sanshi/archive/2012/06/22/2558476.html 若是持久Cookie,Cookie的有效期Expiration属性有当 ...
- 采用Asp.Net的Forms身份验证时,非持久Cookie的过期时间会自动扩展
问题描述 之前没有使用Forms身份验证时,如果在登陆过程中把HttpOnly的Cookie过期时间设为半个小时,总会收到很多用户的抱怨,说登陆一会就过期了. 所以总是会把Cookie过期时间设的长一 ...
- asp.net core中使用cookie身份验证
配置 在 Startup.ConfigureServices 方法中,创建具有 AddAuthentication 和 AddCookie 方法的身份验证中间件服务: services.AddAuth ...
- 也谈Asp.net 中的身份验证
钱李峰 的这篇博文<Asp.net中的认证与授权>已对Asp.net 中的身份验证进行了不错实践.而我这篇博文,是从初学者的角度补充了一些基础的概念,以便能有个清晰的认识. 一.配置安全身 ...
- 简单服务器端Blazor Cookie身份验证的演示
为了演示身份验证如何在服务器端 Blazor 应用程序中工作,我们将把身份验证简化为最基本的元素. 我们将简单地设置一个 cookie,然后读取应用程序中的 cookie. 应用程序身份验证 大多数商 ...
- asp.net的forms身份验证 单用户身份验证
asp.net的forms身份验证 单用户身份验证 首先要配置Web.config文件 <system.web> <authentication mode="Forms& ...
随机推荐
- 数据段描述符和代码段描述符(二)——《x86汇编语言:从实模式到保护模式》读书笔记11
这篇博文,我们编写一个C语言的小程序,来解析数据段或者代码段描述符的各个字段.这样我们阅读原书的代码就会方便一点,只要运行这个小程序,就可以明白程序中定义的数据段或者代码段的描述符了. 这段代码,我用 ...
- mysql 数据库8.0版本,jdbc驱动连接问题
前言 8.0版本的mysql数据的连接 与 5.0的有所不同,下面直接贴出 8.0版本应该有的 jdbc驱动连接,还有 mysql 的jdbc jar包要8.0以上的 内容如下 : jdbc.dri ...
- js实现CkeckBox全选与反选
全选与反选 function SelectAll(){ var check = document.getElementsByTagName("input"); // 获取所有inp ...
- Radix tree--reference
source address:http://en.wikipedia.org/wiki/Radix_tree In computer science, a radix tree (also patri ...
- frp使用总结
笔者所知并成功实现内网穿透的方法: 花生壳 (需要花8块钱,使用花生壳给的二级域名,这里不做介绍) ngrok (免费,但是每次重启服务二级域名会变,付费的$5每月不会变) frp(开源免费,需要有自 ...
- Windows进程间通信--命名管道
1 相关概述 命名管道(Named Pipes)是一种简单的进程间通信(IPC)机制.命名管道可以在同一台计算机的不同进程之间,或者跨越一个网络的不同计算机的不同进程之间的可靠的双向或单向的数据通信. ...
- C#+ObjectArx CAD二次开发(2)
前面开了一个头,这里添加几个功能的实现, //添加图层 private void LoadLayer() { Document acDoc = Application.DocumentManager. ...
- SQL:exec sp_executesql 用法
--這種是無效的過程 declare @sql nvarchar(500), @where nvarchar(500),@i nvarchar(64),@p nvarchar(50),@id int ...
- 初识rbac
一.权限组件 1.项目与应用 一个项目可以有多个应用:一个应用可以在多个项目下:前提:应用是组件. 2.什么是权限? 一个包含正则表达式的url就是一个权限. 可以理解为如下方程式: who what ...
- sass文件处理
sass注释方式有两种: 1.标准的css注释/**/: 2.//双斜杠形式的单行注释(不会被转译): 标准的css注释 双斜杆单行注释 sass文件后缀名有两种: 1.后缀名为sass,不适用用大括 ...