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 身份验证的更多相关文章

  1. asp.net mvc 自定义身份验证

    1.定义身份实体对象 /// <summary> /// 网站用户实体对象 /// </summary> public class DDTPrincipal : IPrinci ...

  2. asp.net mvc 自定义身份验证 2

    控制成员角色 [Authorize(Rroles="Administator,SuperAdmin")] public class StoreManagerController:C ...

  3. 使用JWT的ASP.NET CORE令牌身份验证和授权(无Cookie)——第1部分

    原文:使用JWT的ASP.NET CORE令牌身份验证和授权(无Cookie)--第1部分 原文链接:https://www.codeproject.com/Articles/5160941/ASP- ...

  4. 采用Asp.Net的Forms身份验证时,持久Cookie的过期时间会自动扩展

    原文:http://www.cnblogs.com/sanshi/archive/2012/06/22/2558476.html 若是持久Cookie,Cookie的有效期Expiration属性有当 ...

  5. 采用Asp.Net的Forms身份验证时,非持久Cookie的过期时间会自动扩展

    问题描述 之前没有使用Forms身份验证时,如果在登陆过程中把HttpOnly的Cookie过期时间设为半个小时,总会收到很多用户的抱怨,说登陆一会就过期了. 所以总是会把Cookie过期时间设的长一 ...

  6. asp.net core中使用cookie身份验证

    配置 在 Startup.ConfigureServices 方法中,创建具有 AddAuthentication 和 AddCookie 方法的身份验证中间件服务: services.AddAuth ...

  7. 也谈Asp.net 中的身份验证

    钱李峰 的这篇博文<Asp.net中的认证与授权>已对Asp.net 中的身份验证进行了不错实践.而我这篇博文,是从初学者的角度补充了一些基础的概念,以便能有个清晰的认识. 一.配置安全身 ...

  8. 简单服务器端Blazor Cookie身份验证的演示

    为了演示身份验证如何在服务器端 Blazor 应用程序中工作,我们将把身份验证简化为最基本的元素. 我们将简单地设置一个 cookie,然后读取应用程序中的 cookie. 应用程序身份验证 大多数商 ...

  9. asp.net的forms身份验证 单用户身份验证

    asp.net的forms身份验证  单用户身份验证 首先要配置Web.config文件 <system.web> <authentication mode="Forms& ...

随机推荐

  1. memcached分布式部署

    memcache和memcached两者使用起来几乎一模一样. $mem = new Memcache; $mem->addServer($memcachehost, '11211'); $me ...

  2. keepalive学习之软件设计

    软件架构如下图所示: Keepalived 完全使用标准的ANSI/ISO C写出. 该软件主要围绕一个中央I/O复用分发器而设计,这个I/O复用分发器提供网络实时功能. 主要设计目标着重于从所有的模 ...

  3. bzoj 5340: [Ctsc2018]假面

    Description 题面 Solution 生命值范围比较小,首先维护每一个人在每个血量的概率,从而算出生存的概率,设为 \(a[i]\) 询问时,只需要考虑生存的人数,可以 \(DP\) 设 \ ...

  4. springmvc 登陆拦截器 配合shiro框架使用

    public class LoginHandlerInterceptor extends HandlerInterceptorAdapter{ @Override public boolean pre ...

  5. 阿里云服务器Linux常用命令

    系统信息 arch 显示机器的处理器架构(1) uname -m 显示机器的处理器架构(2) uname -r 显示正在使用的内核版本 dmidecode -q 显示硬件系统部件 - (SMBIOS ...

  6. CompletionService的poll方法

    1.poll():马上返回完成的任务,若没有,则返回null 2.poll(long timeout, TimeUnit unit): 等待timeout时间,如果大于最短任务完成时间,则获取任务结果 ...

  7. 多线程(四)~数据操作的原子性,使用原子性操作AutomicInteger替换非原子性的i++的操作

    这一章,我们要来验证volatile关键字不是原子性的,OK,还是用代码来说话. ①.线程类,操作i++ 500次 package com.multiThread.thread; publicclas ...

  8. Azure 8月众多新版本公布

    Azure 8月新发布:IoT 中心S3 版,Azure 热/冷存储层,DocumentDB,SQL Server Stretch Database, MySQL 5.7, Cloud Foundry ...

  9. Azure 11 月新公布

    Azure 11 月新发布:Apple FairPlay Streaming, 应用服务(App Service), 虚拟机规模集(VMSS) Azure 媒体服务的 Apple FairPlay S ...

  10. ul自适应li问题

    内容提要: li浮动时ul高度为0,解决ul自适应高度的几种方法 在网页设计中,常常需要对li标签做浮动效果,但是在不同浏览器中会遇到兼容性问题,比如IE中会出现ul高度为0的情况,是效果不能达到预期 ...