• 最简实例演示asp.net5中用户认证和授权(3)


    上接:

    最简实例演示asp.net5中用户认证和授权(2)

    在实现了角色的各种管理接口后,下一步就是实现对用户的管理,对用户管理的接口相对多一些,必须要实现的有如下三个:

    1 public interface IUserRoleStore<TUser> : IUserStore<TUser>, IDisposable where TUser : class
    2 
    3 public interface IUserPasswordStore<TUser> : IUserStore<TUser>, IDisposable where TUser : class
    4 
    5 public interface IQueryableUserStore<TUser> : IUserStore<TUser>, IDisposable where TUser : class

    第一个是关于用户和角色关系的接口,定义了和角色相关的几个方法。

    第二个是关于密码的,定义了用户密码的读取和设置等方法。

    最后一个是关于用户本身的,定义了用户增删改查等方法。

    下面是具体的代码:

      1 public class HDUserStore<TUser> :
      2         IUserRoleStore<TUser>,
      3         IUserPasswordStore<TUser>,
      4         IQueryableUserStore<TUser>
      5         where TUser : HDUser, new()
      6     {
      7         /// <summary>
      8         /// 存储用户列表
      9         /// </summary>
     10         private readonly Dictionary<string, TUser> _users = new Dictionary<string, TUser>();
     11 
     12         public IQueryable<TUser> Users
     13         {
     14             get
     15             {
     16                 if (_users.Count == 0)
     17                 {
     18                     //生成用户
     19                     TUser user = CreateNewUser("1", "daxia", "qingdao");
     20                     //设置用户角色
     21                     user.Roles.Add(new HDUserRole() { UserId = "1", RoleId = "power" });
     22                     _users.Add(user.Id, user);
     23 
     24                     user = CreateNewUser("2", "aspnet5", "mvc6");
     25                     user.Roles.Add(new HDUserRole() { UserId = "2", RoleId = "admin" });
     26                     _users.Add(user.Id, user);
     27                 }
     28                 return _users.Values.AsQueryable();
     29             }
     30         }
     31 
     32         /// <summary>
     33         /// 生成用户
     34         /// </summary>
     35         /// <param name="id"></param>
     36         /// <param name="name"></param>
     37         /// <param name="pwd"></param>
     38         /// <returns></returns>
     39         private TUser CreateNewUser(string id, string name, string pwd)
     40         {
     41             TUser user = new TUser();
     42             user.PassWord = pwd;
     43             user.Id = id;
     44             user.UserName = name;
     45             user.NormalizedUserName = name.ToUpper();
     46             PasswordHasher<TUser> hash = new PasswordHasher<TUser>();
     47             user.PasswordHash = hash.HashPassword(user, user.PassWord);
     48 
     49             return user;
     50         }
     51         
     52         public Task AddToRoleAsync(TUser user, string roleId, CancellationToken cancellationToken)
     53         {
     54             user.Roles.Add(new HDUserRole { RoleId = roleId, UserId = user.Id });
     55             return Task.FromResult(0);
     56         }
     57 
     58         public Task<IdentityResult> CreateAsync(TUser user, CancellationToken cancellationToken)
     59         {
     60             _users[user.Id] = user;
     61             return Task.FromResult(IdentityResult.Success);
     62         }
     63 
     64         public Task<IdentityResult> DeleteAsync(TUser user, CancellationToken cancellationToken)
     65         {
     66             if (user == null || !_users.ContainsKey(user.Id))
     67             {
     68                 throw new InvalidOperationException("Unknown user");
     69             }
     70             _users.Remove(user.Id);
     71             return Task.FromResult(IdentityResult.Success);
     72         }
     73 
     74         public void Dispose()
     75         {
     76 
     77         }
     78 
     79         public Task<TUser> FindByIdAsync(string userId, CancellationToken cancellationToken)
     80         {
     81             if (_users.ContainsKey(userId))
     82             {
     83                 return Task.FromResult(_users[userId]);
     84             }
     85             return Task.FromResult<TUser>(null);
     86         }
     87 
     88         public Task<TUser> FindByNameAsync(string userName, CancellationToken cancellationToken)
     89         {
     90             return
     91                 Task.FromResult(
     92                     Users.FirstOrDefault(u => u.UserName.ToUpper() == userName.ToUpper()));
     93         }
     94         
     95         public Task<string> GetNormalizedUserNameAsync(TUser user, CancellationToken cancellationToken)
     96         {
     97             return Task.FromResult(user.NormalizedUserName);
     98         }
     99 
    100         public Task<string> GetPasswordHashAsync(TUser user, CancellationToken cancellationToken)
    101         {
    102             return Task.FromResult(user.PasswordHash);
    103         }
    104 
    105         public Task<IList<string>> GetRolesAsync(TUser user, CancellationToken cancellationToken)
    106         {
    107             return Task.FromResult<IList<string>>(user.Roles.Select(ur => ur.RoleId).ToList());
    108         }
    109 
    110         public Task<string> GetUserIdAsync(TUser user, CancellationToken cancellationToken)
    111         {
    112             return Task.FromResult(user.Id);
    113         }
    114 
    115         public Task<string> GetUserNameAsync(TUser user, CancellationToken cancellationToken)
    116         {
    117             return Task.FromResult(user.UserName);
    118         }
    119 
    120         public Task<IList<TUser>> GetUsersInRoleAsync(string roleName, CancellationToken cancellationToken)
    121         {
    122             if (String.IsNullOrEmpty(roleName))
    123             {
    124                 throw new ArgumentNullException(nameof(roleName));
    125             }
    126 
    127             return Task.FromResult<IList<TUser>>(Users.Where(u => (u.Roles.Where(x => x.RoleId == roleName).Count() > 0)).Select(x => x).ToList());
    128 
    129         }
    130 
    131         public Task<bool> HasPasswordAsync(TUser user, CancellationToken cancellationToken)
    132         {
    133             return Task.FromResult(user.PassWord != null);
    134         }
    135 
    136         public Task<bool> IsInRoleAsync(TUser user, string roleName, CancellationToken cancellationToken)
    137         {
    138             return Task.FromResult(user.Roles.Any(ur => ur.RoleId == roleName));
    139         }
    140 
    141         public Task RemoveFromRoleAsync(TUser user, string roleName, CancellationToken cancellationToken)
    142         {
    143             var roleEntity = user.Roles.SingleOrDefault(ur => ur.RoleId == roleName);
    144             if (roleEntity != null)
    145             {
    146                 user.Roles.Remove(roleEntity);
    147             }
    148             return Task.FromResult(0);
    149         }
    150 
    151         public Task SetNormalizedUserNameAsync(TUser user, string normalizedName, CancellationToken cancellationToken)
    152         {
    153             user.NormalizedUserName = normalizedName;
    154             return Task.FromResult(0);
    155         }
    156 
    157         public Task SetPasswordHashAsync(TUser user, string passwordHash, CancellationToken cancellationToken)
    158         {
    159             user.PasswordHash = passwordHash;
    160             return Task.FromResult(0);
    161         }
    162 
    163         public Task SetUserNameAsync(TUser user, string userName, CancellationToken cancellationToken)
    164         {
    165             user.UserName = userName;
    166             return Task.FromResult(0);
    167         }
    168 
    169         public Task<IdentityResult> UpdateAsync(TUser user, CancellationToken cancellationToken)
    170         {
    171             _users[user.Id] = user;
    172             return Task.FromResult(IdentityResult.Success);
    173         }
    174     }

    代码本身比较易懂,这一块要注意的是在我们生成用户的同时,把角色也附加到了用户上面,当然,这一块也都可以通过自定义的数据库实现数据存取。

    下篇:

    最简实例演示asp.net5中用户认证和授权(4) 

  • 相关阅读:
    常用linux命令及其设置
    shell脚本编写步骤及其常用命令和符号
    浏览器访问php脚本通过sendmail用mail函数发送邮件
    windows server 定期备份数据库脚本
    图片垂直水平居中
    "!function",自执行函数表达式
    jQuery(function(){})与(function(){})(jQuery) 的区别
    在Windows Server 2019通过Docker Compose部署Asp.Net Core
    Redis集群同步问题
    webapi跨域使用session
  • 原文地址:https://www.cnblogs.com/aspnet5/p/4874732.html
Copyright © 2020-2023  润新知