利用Asp.Net的Identity控制登录权限

利用Asp.Net的Identity控制登录权限

2023年6月20日发(作者:)

利⽤的Identity控制登录权限⼀直对的MVC中的AuthorizeAttribute控制登录感到很困惑,这⼏天研究了⼀下,⼤概了解了⼀下整个流程,写出来记录⼀下。场景:1.即使没有登录,也可以访问⼀些可以匿名访问的Action。   2.对于登录来说,如果在某个地⽅登录成功,那么在缓存没清除或者过期之前,下次再进⼊该系统的话,正常情况是不需要再次登录的。   3.对于需要登录的Action,如果匿名请求,那么需要跳转到登录页⾯。

如以下流程图:

这张流程图只是⼤概描述了⼀下登录的过程。还有其他的细节,暂不考虑。

再说⼀下AuthorizeAttribute的验证原理:验证登录的机制,⽆⾮是根据请求的数据判断⽤户是否已经登录。AuthorizeAttribute进⾏权限判断的依据是如果登录成功在浏览器中设置加密Cookie,每次发送请求都把Cookie发送回服务器进⾏验证。我根据⾃⼰的理解。画了如下流程图。下⾯只列出部分关键代码:1.创建User类,继承⾃,实现UserName属性。 public class User : IUser { public User(List tels, List mails, string password) { Id = d().ToString("N"); Tels = tels; Mails = mails; Password = password; } public string Id { get; set; } public string Password { get; set; } public string Name { get; set; } public string Address { get; set; } public List Tels { get; set; } public List Mails { get; set; } public string Company { get; set; } public string Job { get; set; } public string Image { get; set; } public string UserName { get { return Name; } set { Name = value; } } }User

2.创建了IUserService接⼝,继承⾃tore;; public interface IUserService : IUserStore { bool RegisterByTel(string tel, string pwd); bool RegisterByMail(string mail, string pwd); bool LoginByTel(User user); bool LoginByMail(string mail, string pwd); bool UpdateUser(LinkMan linkMan); bool LoginByMail(User user); }IUserService

3.创建⾃定义验证其,继承⾃AuthorizeAttribute,并且添加到全局过滤: public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { (new HandleErrorAttribute()); (new MyAuthorizeAttribute()); } } public class MyAuthorizeAttribute : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { if (!enticated) // 未登录 { var attr = tomAttributes(typeof(AllowAnonymousAttribute), true); bool allowAnonymous = (a => a != null); if (allowAnonymous) return; var identityName = ; if (OrEmpty(identityName)) { = new RedirectResult("/Default/Login/Index"); } } orization(filterContext); } }FilterConfig该过滤器,只是简单的过滤器,没太复杂的业务逻辑。

4.在登录成功后,设置标记。 me = telOrMail; var identity = new nager(rService()).CreateIdentityAsync(user, ationCookie).Result; nContext().(new AuthenticationProperties() { IsPersistent = true }, identity);

LoginSuccess这⾥只列出了关键代码,没列出登录的所有代码,

以上的这些步骤就实现了所列出的3个场景。

发布者:admin,转转请注明出处:http://www.yc00.com/news/1687250393a48.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信