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& ...
随机推荐
- netstat参数
1.功能与说明 netstat 用于显示linux中各种网络相关信息.如网络链接.路由表.接口状态链接.多播成员等等. 定义:Netstat是在内核中访问网络及相关信息的程序,它能提供TCP连接,TC ...
- 通过JavaScript动态生成html控件
示例代码 <html> <head> <meta http-equiv="Content-Type" content="text/html& ...
- Distinct 去掉重复 order by
语法: select distinct user from book select * from sdudant order by sex asc,sNo 从表sdudant查找已性别升序排序,性别相 ...
- 通过js操作样式(评分)
<style> td{ font-size:50px; color:yellow; cursor:pointer; } </style> <script type=&qu ...
- Android使用主题属性引发的问题
最近在做一个项目的Porting.直接改变了应用的Theme,最没有仔细的检查.结果应用在某些场景下直接就Crash了.还好,通过Log可以看到是在Inflate某个资源的时候出错导致的.通过定位资源 ...
- CSS之背景的填充范围
1.资料:CSS2.1 进行了更正:元素的背景是内容.内边距和边框区的背景 2.也就是说背景颜色,background-color:这些会填充内边距和边框border, 而不会填充外边框margin的 ...
- 小程序 - 图片列表显示lazyload效果
在做一个短视频平台,涉及到的都是一些列表模块.因为小程序没有提供lazyload api,所以只能自己写一个了... 开发涉及 <scroll-view></scroll-view& ...
- 【Mood-15】DailyBuild 1月
keywords: AsyncImageLoader universal-image-loader 2015-01-07 AsyncImageLoader:异步动态加载网络图片 类似listview ...
- C++字符分割
AfxExtractSubString 表头: <afxwin.h> BOOL AFXAPI AfxExtractSubString ( CString& rString, LPC ...
- SQL Server 的 主键 解决方案 NEWID() , 自增ID
在 SQL Server 表的主键有自增Id ,和 GUID. 1. 自增Id 优点:索引空间小,索引连续.在大量数据插入的时候性能有特别大的优势. 缺点:可移植性差,在数据迁移的时候. 2. G ...