用户验证之自定义身份验证
这是今天在课堂上演示的例子代码,自定义身份验证的简单做法是通过GenericPrinciple和GenericIdentity实现,也可以通过自定义Principle和Identity实现。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Security; using System.Security.Principal; namespace _03_CustomAuthentication { class Program { static void Main(string[] args) { //这里实现自定义验证(GenericPrinciple) //要求用户输入用户名和密码 Console.WriteLine("请输入用户名:"); string username = Console.ReadLine(); Console.WriteLine("请输入密码:"); string password = Console.ReadLine(); //现在的做法是直接硬编码来做身份验证 if (AuthenticateUser(username, password)) { Console.WriteLine("欢迎使用:{0}!", username); //GenericPrincipal p =(GenericPrincipal)Thread.CurrentPrincipal; //Console.WriteLine("当前您是属于管理员:{0}", // p.IsInRole("Admin")); MyPrinciple p = (MyPrinciple)Thread.CurrentPrincipal; MyIdentity i = p.Identity as MyIdentity; Console.WriteLine("当前您是属于管理员:{0}", p.IsInRole("Admin")); Console.WriteLine("用户的角色列表:"); foreach (var item in i.Roles) { Console.WriteLine(item); } } else Console.WriteLine("你不是合法用户"); Console.Read(); } private static bool AuthenticateUser(string username, string password) { if (username == "chenxizhang" && password == "password") { #region GenericIdentity //GenericIdentity identity = new GenericIdentity( // username,"Custom"); //GenericPrincipal principal = new GenericPrincipal( // identity, // new[] { "Admin" }); //Thread.CurrentPrincipal = principal; #endregion MyIdentity identity = new MyIdentity( username, new[] { "Admin" }); MyPrinciple principle = new MyPrinciple( identity, identity.Roles); Thread.CurrentPrincipal = principle; return true; } return false; } } class MyPrinciple : IPrincipal { public MyPrinciple(IIdentity identity, string[] roles) { _identity = identity; _roles = roles; } string[] _roles; private IIdentity _identity; private MyPrinciple() { }//禁用默认构造器 #region IPrincipal 成员 public IIdentity Identity { get { return _identity; } } public bool IsInRole(string role) { return _roles.Contains(role); } #endregion } class MyIdentity : IIdentity { public MyIdentity(string name, string[] roles) { _name = name; _roles = roles; } private string[] _roles; public string[] Roles { get { return _roles; } } private MyIdentity() { } #region IIdentity 成员 public string AuthenticationType { get { return "自定义验证"; } } public bool IsAuthenticated { get { return true; } } private string _name; public string Name { get { return _name; } } #endregion } }