DefaultResourceOwnerPasswordValidator.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using IdentityModel;
  2. using IdentityServer4.Models;
  3. using IdentityServer4.Validation;
  4. using Long.Common.Enums;
  5. using Long.DAO.Basedata;
  6. using Long.Utils.Encryptor;
  7. using System.Security.Claims;
  8. namespace Auth
  9. {
  10. public class DefaultResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
  11. {
  12. private readonly ISystemUserDatabase _systemUserDatabase = new SystemUserDatabase();
  13. private readonly IUserDatabase _userDatabase = new UserDatabase();
  14. private string _encryptionKey;
  15. public DefaultResourceOwnerPasswordValidator(IConfiguration configuration)
  16. {
  17. this._encryptionKey = configuration["EncryptorKey"] ?? "";
  18. }
  19. public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
  20. {
  21. // 是否登录
  22. var isLogin = false;
  23. // 内码
  24. string id = string.Empty;
  25. if (context.Request.ClientId == UserTypeEnum.Admin.ToString().ToLower())
  26. {
  27. // 系统用户登录
  28. var systemUser = await _systemUserDatabase.GetByUserNameAsync(context.UserName);
  29. if (systemUser != null && DESEncryptor.Encrypt(context.Password, _encryptionKey) == systemUser.Password)
  30. {
  31. isLogin = true;
  32. id = systemUser.Id.ToString();
  33. }
  34. }
  35. else if (context.Request.ClientId == UserTypeEnum.User.ToString().ToLower())
  36. {
  37. // 普通用户登录
  38. var user = await _userDatabase.GetByUserNameAsync(context.UserName);
  39. if (user != null && DESEncryptor.Encrypt(context.Password, _encryptionKey) == user.Password)
  40. {
  41. isLogin = true;
  42. id = user.Id.ToString();
  43. }
  44. }
  45. if (isLogin)
  46. {
  47. var claims = new List<Claim>()
  48. {
  49. new Claim(JwtClaimTypes.Id, id),
  50. new Claim(JwtClaimTypes.PreferredUserName, context.UserName)
  51. };
  52. context.Result = new GrantValidationResult(id, OidcConstants.AuthenticationMethods.Password, claims);
  53. return;
  54. }
  55. context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant);
  56. }
  57. }
  58. }