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& ...
随机推荐
- Android触摸事件传递机制
简单梳理一下Android触摸事件传递机制的知识点. 一.View与ViewGroup的关系 View和ViewGroup二者的继承关系如下图所示: View是Android中最基本的一种UI组件,它 ...
- 原生JS写的ajax函数
参照JQuery中的ajax功能,用原生JS写了一个ajax,功能相对JQuery要少很多,不过基本功能都有,包括JSONP. 调用的方式分为两种: 1. ajax(url, {}); 2. ajax ...
- 深入理解JavaScript系列(24):JavaScript与DOM(下)
介绍 上一章我们介绍了JavaScript的基本内容和DOM对象的各个方面,包括如何访问node节点.本章我们将讲解如何通过DOM操作元素并且讨论浏览器事件模型. 本文参考:http://net.tu ...
- 1个示例 学会 mvc 常用标签
HtmlHelper用法大全3:Html.LabelFor.Html.EditorFor.Html.RadioButtonFor.Html.CheckBoxFor @Html.***For:为由指定 ...
- Java日志框架解析及实战分析
转载自: https://zhuanlan.zhihu.com/p/24272450 https://zhuanlan.zhihu.com/p/24275518 作为Java程序员,幸运的是,Java ...
- Baseball Game
You're now a baseball game point recorder. Given a list of strings, each string can be one of the 4 ...
- Java程序员应该知道的linux命令
1.查看Java进程:ps -ef|grep java,ps auxf|grep jva; 2.杀死所有Java进程: pkill java, kill -9 进程ID: 3.进入目录:cd /usr ...
- windows下使用xerces -c解析XML
windows下使用Xerces-C++解析XML 前景提要 最近工作中遇到收到的数据为xml格式的情况,考虑到xml解析应该是个很常用的功能,应该有开源的lib库可以使用,于是就在网上找了找,果然发 ...
- PowerDesigner 连接数据库(以MySQL)为例
- Java常用Json库性能对比
Java对于处理JSON数据的序列化与反序列化目前常用的类库有Gson.FastJSON.Jackson.jettison以及json-lib.在这里我们将对这些类库在json序列化与反序列化方面的性 ...