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& ...
随机推荐
- Excel&&word&&PPT
1. Excel 1.1 制作下拉框 选中单元格或列--> 菜单"数据" --> "数据验证"-->"设置" --> ...
- 内行看门道:看似“佛系”的《QQ炫舞手游》,背后的音频技术一点都不简单
欢迎大家前往腾讯云+社区,获取更多腾讯海量技术实践干货哦~ 本文由腾讯游戏云发表于云+社区专栏 3月14日,腾讯旗下知名手游<QQ炫舞>正式上线各大应用商店,并迅速登上App Store免 ...
- 腾讯蔡晨:十年沉淀,腾讯iOA为企业安全保驾护航
欢迎大家前往腾讯云+社区,获取更多腾讯海量技术实践干货哦~ 背景:5月23-24日,以"焕启"为主题的腾讯"云+未来"峰会再广州召开,广东省各级政府机构领导.海 ...
- Java入门系列-07-从控制台中接收输入
这篇文章帮你使用Scanner类从控制台接收输入 从控制台接收字符串 敲一敲: import java.util.Scanner; public class DemoScanner { public ...
- java使用commons-fileupload进行文件上传
java中使用文件上传时需要使用特定的类库,这里使用commons-files类库进行文件上传,在http://commons.apache.org/proper/commons-fileupload ...
- java常用API之DateFormat
DateFormat 类: DateFormat 类是日期/时间格式化子类的抽象类,它以与语言无关的方式格式化并解析日期或时间.日期/时间格式化子类(如 SimpleDateFormat类)允许进行格 ...
- github使用手册
1.git init 2.git add README.md (增加文件夹/文件:git add dir/files) 3.git commit -m "注释内容” 4.git push - ...
- 检测IE浏览器兼容Edge模式及IE11
document.documentMode || +(navigator.userAgent.match(/MSIE (\d+)/) && RegExp.$1) 判断布尔值
- 日期函数new Date()浏览器兼容性问题
项目上与时间相关的地方特别多,与时间格式相关都使用了moment.js轻量级日期处理库,在开发中出现了几次浏览器兼容性问题,所以总结一下new Date()和moment.js在各大浏览器中兼容性问题 ...
- PHP连接MySQL数据库的几种方式
PHP 5 及以上版本建议使用以下方式连接 MySQL : MySQLi :MySQLi 只针对 MySQL 数据库,MySQLi 还提供了 API 接口. PDO (PHP Data Objects ...