




已阅读5页,还剩4页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
ASP NET MVC 窗体身份验证及角色权限管理示例 窗体身份验证及角色权限管理示例 前言前言 本来使用 Forms Authentication 进行用户验证的方式是最常见的 但系统地阐明其方法的文章并 不多见 网上更多的文章都是介绍其中某一部分的使用方法或实现原理 而更多的朋友则发文询问如何从 头到尾完整第实现用户的注册 登录 因此 Anders Liu 在这一系列文章中计划通过一个实际的例子 介绍如何基于 Forms Authentication 实现 l 用户注册 包括密码的加密存储 l 用户登录 包括密码的验证 设置安全 Cookie l 用户实体替换 使用自己的类型作为 HttpContext User 的类型 有关 Forms Authentication 的原理等内容不属于本文的讨论范畴 大家可以通过在 Google 等搜 索引擎中输入 Forms Authentication Forms 身份验证 窗体身份验证 等关键词来查看更多资源 本文仅从实用的角度介绍如何使用这一技术 不使用不使用 Membership 本文介绍的实现方式不依赖 ASP NET 2 0 提供的 Membership 功能 这主要是因为 如果使用 Membership 就必须用 aspnet regsql exe 实用工具配置数据库 否则就得自己写自定义的 MembershipProvider 如果用 aspnet regsql exe 配置数据库 就会导致数据库中出现很多我们实际并不需要的表或字段 此外更重要的是 默认的 SqlMembershipProvider 给很多数据表添加了 ApplicationID 列 其初衷可 能是希望可以将多个应用程序的用户全部放在一个库里 但又能彼此隔离 但实际情况是 每个应用程序 都在其自身的数据库中保存用户数据 因此 引入这个 ApplicationID 无端地在每次查找用户时增加了 额外的条件 另一方面 如果考虑自己实现一个 MembershipProvider 因为工作量巨大 有点得不偿失 但是 如果不使用 Membership 也就无法享受 ASP NET 2 0 中新增的 Login 等控件的便利了 与与 Forms Authentication 相关的配置相关的配置 在 web config 文件中 配置节用于对验证进行配置 为 节点提供 mode Forms 属性可以启用 Forms Authentication 一个典型的 配置节如下所示 以上代码使用的均是默认设置 换言之 如果你的哪项配置属性与上述代码一致 则可以省略该属性 例如 下面依次介绍一下各种属性 l name Cookie 的名字 Forms Authentication 可能会在验证后将用户凭证放在 Cookie 中 name 属性决定了该 Cookie 的名字 通过 FormsAuthentication FormsCookieName 属性可以得到 该配置值 稍后介绍 FromsAuthentication 类 l loginUrl 登录页的 URL 通过 FormsAuthentication LoginUrl 属性可以得到该配置值 当调用 FormsAuthentication RedirectToLoginPage 方法时 客户端请求将被重定向到该属性所指定的页面 loginUrl 的默认值为 login aspx 这表明即便不提供该属性值 ASP NET 也会尝试到站点根目录下寻 找名为 login aspx 的页面 l defaultUrl 默认页的 URL 通过 FormsAuthentication DefaultUrl 属性得到该配置值 l protection Cookie 的保护模式 可取值包括 All 同时进行加密和数据验证 Encryption 仅加 密 Validation 仅进行数据验证 和 None 为了安全 该属性通常从不设置为 None l timeout Cookie 的过期时间 l path Cookie 的路径 可以通过 FormsAuthentication FormsCookiePath 属性得到该配置值 l requireSSL 在进行 Forms Authentication 时 与服务器交互是否要求使用 SSL 可以通过 FormsAuthentication RequireSSL 属性得到该配置值 l slidingExpiration 是否启用 弹性过期时间 如果该属性设置为 false 从首次验证之后过 timeout 时间后 Cookie 即过期 如果该属性为 true 则从上次请求该开始过 timeout 时间才过期 这 意味着 在首次验证后 如果保证每 timeout 时间内至少发送一个请求 则 Cookie 将永远不会过期 通过 FormsAuthentication SlidingExpiration 属性可以得到该配置值 l enableCrossAppRedirects 是否可以将以进行了身份验证的用户重定向到其他应用程序中 通过 FormsAuthentication EnableCrossAppRedirects 属性可以得到该配置值 为了安全考虑 通常总是 将该属性设置为 false l cookieless 定义是否使用 Cookie 以及 Cookie 的行为 Forms Authentication 可以采用两种方 式在会话中保存用户凭据信息 一种是使用 Cookie 即将用户凭据记录到 Cookie 中 每次发送请求时 浏览器都会将该 Cookie 提供给服务器 另一种方式是使用 URI 即将用户凭据当作 URL 中额外的查询 字符串传递给服务器 该属性有四种取值 UseCookies 无论何时都使用 Cookie UseUri 从不 使用 Cookie 仅使用 URI AutoDetect 检测设备和浏览器 只有当设备支持 Cookie 并且在浏览 器中启用了 Cookie 时才使用 Cookie 和 UseDeviceProfile 只检测设备 只要设备支持 Cookie 不管 浏览器是否支持 都是用 Cookie 通过 FormsAuthentication CookieMode 属性可以得到该配置值 通过 FormsAuthentication CookiesSupported 属性可以得到对于当前请求是否使用 Cookie 传递用 户凭证 l domain Cookie 的域 通过 FormsAuthentication CookieDomain 属性可以得到该配置值 以上针对 节点的介绍非常简略 基本上是 Anders Liu 个人对于文档进行的额外说明 有关节点的更多说明 请参见 MSDN 文档 FormsAuthentication 类类 FormsAuthentication 类用于辅助我们完成窗体验证 并进一步完成用户登录等功能 该类位于 system web dll 程序集的 System Web Security 命名空间中 通常在 Web 站点项目中可以直接使用 这个类 如果是在类库项目中使用这个类 请确保引用了 system web dll 前一节已经介绍了 FormsAuthentication 类的所有属性 这一节将介绍该类少数几个常用的方法 RedirectToLoginPage 方法用于从任何页面重定向到登录页 该方法有两种重载方式 public static void RedirectToLoginPage public static void RedirectToLoginPage string extraQueryString 两种方式均会使浏览器重定向到登录页 登录页的 URL 由节点的 loginUrl 属性指出 第二种重载方式还能够提供额外的查询字符串 RedirectToLoginPage 通常在任何非登录页的页面中调用 该方法除了进行重定向之外 还会向 URL 中附加一个 ReturnUrl 参数 该参数即为调用该方法时所在的页面的 URL 地址 这是为了方便登录 后能够自动回到登录前所在的页面 RedirectFromLoginPage 方法用于从登录页跳转回登录前页面 这个 登录前 页面即由访问登录页 时提供的 ReturnUrl 参数指定 如果没有提供 ReturnUrl 参数 例如 不是使用 RedirectToLoginPage 方法而是用其他手段重定向到或直接访问登录页时 则该方法会自动跳转到由 节点的 defaultUrl 属性所指定的默认页 此外 如果节点的 enableCrossAppRedirects 属性被设置为 false ReturnUrl 参数所 指定的路径必须是当前 Web 应用程序中的路径 否则 如提供其他站点下的路径 也将返回到默认页 RedirectFromLoginPage 方法有两种重载形式 public static void RedirectFromLoginPage string userName bool createPersistentCookie public static void RedirectFromLoginPage string userName bool createPersistentCookie string strCookiePath userName 参数表示用户的标识 如用户名 用户 ID 等 createPersistentCookie 参数表示是 否 记住我 strCookiePath 参数表示 Cookie 路径 RedirectFromLoginPage 方法除了完成重定向之外 还会将经过加密 是否加密取决于 节点的 protection 属性 的用户凭据存放到 Cookie 或 Uri 中 在后续访问中 只要 Cookie 没有过期 则将可以通过 HttpContext User Identity Name 属性得到这里传入的 userName 属性 此外 FormsAuthentication 还有一个 SignOut 方法 用于完成用户注销 其原理是从 Cookie 或 Uri 中移除用户凭据 好了 至此所需要掌握的基础知识就齐备了 接下来我们将实现用户注册 登录等功能 ASP NET MVC 建立 ASP NET 基础之上 很多 ASP NET 的特性 如窗体身份验证 成员资格 在 MVC 中可以直接使用 本文旨在提供可参考的代码 不会涉及这方面太多理论的知识 本文仅使用 ASP NET 的窗体身份验证 不会使用它的 成员资格 Membership 和 角色管理 RoleManager 原因有二 一是不灵活 二是和 MVC 关系不太 一 示例项目 User cs 是模型文件 其中包含了 User 类 public class User public int ID get set public string Name get set public string Password get set public string Roles get set UserRepository 为数据存取类 为了演示方便 并没有连接数据库 而是使用一个数组来作为数据源 public class UserRepository private static User usersForTest new new User ID 1 Name bob Password bob Roles new employee new User ID 2 Name tom Password tom Roles new manager new User ID 3 Name admin Password admin Roles new admin public bool ValidateUser string userName string password return usersForTest Any u u Name userName public string GetRoles string userName return usersForTest Where u u Name userName Select u u Roles FirstOrDefault public User GetByNameAndPassword string name string password return usersForTest FirstOrDefault u u Name name 二 用户登录及身份验证 方式一方式一 修改修改 AccountController 原有 AccountController 为了实现控制反转 对窗体身份验证进行了抽 象 为了演示方便 我去除了这部分 以及注册及修改密码部分 public class AccountController Controller private UserRepository repository new UserRepository public ActionResult LogOn return View HttpPost public ActionResult LogOn LogOnModel model string returnUrl if ModelState IsValid if repository ValidateUser model UserName model Password FormsAuthentication SetAuthCookie model UserName model RememberMe if String IsNullOrEmpty returnUrl return Redirect returnUrl else return RedirectToAction Index Home else ModelState AddModelError 用户名或密码不正确 return View model public ActionResult LogOff FormsAuthentication SignOut return RedirectToAction Index Home 修改修改 Global asax public class MvcApplication System Web HttpApplication public MvcApplication AuthorizeRequest new EventHandler MvcApplication AuthorizeRequest void MvcApplication AuthorizeRequest object sender EventArgs e IIdentity id Context User Identity if id IsAuthenticated var roles new UserRepository GetRoles id Name Context User new GenericPrincipal id roles 给 MvcApplication 增加构造函数 在其中增加 AuthorizeRequest 事件的处理函数 代码下载 Mvc FormsAuthentication RolesAuthorization 1 rar 243KB 方式二方式二 此方式将用户的角色保存至用户 Cookie 使用到了 FormsAuthenticationTicket 修改修改 AccountController public class AccountController Controller private UserRepository repository new UserRepository public ActionResult LogOn return View HttpPost public ActionResult LogOn LogOnModel model string returnUrl if ModelState IsValid User user repository GetByNameAndPassword model UserName model Password if user null FormsAuthenticationTicket ticket new FormsAuthenticationTicket 1 user Name DateTime Now DateTime Now Add FormsAuthentication Timeout model RememberMe user Roles Aggregate i j i j HttpCookie cookie new HttpCookie FormsAuthentication FormsCookieName FormsAuthentication Encrypt ticket Response Cookies Add cookie if String IsNullOrEmpty returnUrl return Redirect returnUrl else return RedirectToAction Index Home else ModelState AddModelError 用户名或密码不正确 return View model public ActionResult LogOff FormsAuthentication SignOut return RedirectToAction Index Home 修改修改 Global asax public class MvcApplication System Web HttpApplication public MvcApplication AuthorizeRequest new EventHandler MvcApplication AuthorizeRequest void MvcApplication AuthorizeRequest object sender EventArgs e var id Context User Identity as FormsIdentity if id null Context User new GenericPrincipal id roles 代码下载 Mvc FormsAuthentication RolesAuthorization 2 rar 244KB 三 角色权限 使用任一种方式后 我们就可以在 Controller 中使用 AuthorizeAttribute 实现基于角色的权限管理了 Authorize Roles employee manager public ActionResult Index1 return View Authorize Roles manager public ActionResult Index2 return View Authorize Users admin Roles admin public ActionResult Index3 return View 四 简要说明 MVC 使用 HttpContext User 属性进行来进行实现身份验证及角色管理 同样 AuthorizeAttribute 也根据 HttpContext User 进行角色权限验证 因些不要在用户登录后 将相关用户信息保存在 Sessi
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 餐饮业人才短缺现状与2025年新趋势培养路径研究报告
- 申请实践活动方案
- 美容院老板抽奖活动方案
- 矿业公司拓展活动方案
- 端午节企业文化活动方案
- 端午蔬菜活动方案
- 社教活动进社区活动方案
- 社群服务党建活动方案
- 餐饮业2025年突发事件应急物资储备与管理报告
- 碳酸饮料活动方案
- GB/T 21063.4-2007政务信息资源目录体系第4部分:政务信息资源分类
- 机修车间岗位廉洁风险点及防范措施表
- 全新版尹定邦设计学概论1课件
- 牙及牙槽外科
- 文物建筑保护修缮专项方案
- 万用表 钳形表 摇表的使用课件
- 63T折弯机使用说明书
- 170位真实有效投资人邮箱
- 工程力学ppt课件(完整版)
- 《区域经济学》讲义(1)课件
- 船模制作教程(课堂PPT)课件(PPT 85页)
评论
0/150
提交评论