AuthorizeGenerator.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using MapsterMapper;
  2. using Microsoft.Extensions.DependencyInjection;
  3. namespace NewRock.Sdk.Security
  4. {
  5. public interface IAuthorizeGenerator
  6. {
  7. NewRockAuthorize GetAuthorize(string key, int expired);
  8. }
  9. public class AuthorizeGenerator : IAuthorizeGenerator
  10. {
  11. private readonly IServiceScopeFactory _serviceScopeFactory;
  12. private CreationNewRockAuthorize? _creationAuthorize;
  13. public AuthorizeGenerator(IServiceScopeFactory serviceScopeFactory)
  14. {
  15. _serviceScopeFactory = serviceScopeFactory;
  16. }
  17. public NewRockAuthorize GetAuthorize(string key, int expired)
  18. {
  19. using var scope = _serviceScopeFactory.CreateScope();
  20. //var options = scope.ServiceProvider.GetService<IOptionsSnapshot<NewRockConfiguration>>();
  21. var mapper = scope.ServiceProvider.GetService<IMapper>();
  22. //var key = options.Value.ReceiveKey;
  23. if (_creationAuthorize == null)
  24. {
  25. var authorize = GenerateAuthorize(key);
  26. _creationAuthorize = mapper.Map<CreationNewRockAuthorize>(authorize);
  27. return authorize;
  28. }
  29. // 检查过期时间
  30. //var expired = options.Value.Expired;
  31. if ((DateTime.Now - _creationAuthorize.CreationTime).TotalSeconds + 5 >= expired)
  32. {
  33. _creationAuthorize = mapper.Map<CreationNewRockAuthorize>(GenerateAuthorize(key));
  34. }
  35. return mapper.Map<NewRockAuthorize>(_creationAuthorize);
  36. }
  37. /// <summary>
  38. /// 生成一个校验信息
  39. /// </summary>
  40. /// <returns></returns>
  41. private NewRockAuthorize GenerateAuthorize(string key)
  42. {
  43. var nonce = Encryptor.GenerateRandomNumber();
  44. var timestamp = Encryptor.GenerateTimestamp();
  45. var signature = Encryptor.Signature(key, nonce, timestamp);
  46. return new NewRockAuthorize
  47. {
  48. Nonce = nonce,
  49. Timestamp = timestamp,
  50. Signature = signature
  51. };
  52. }
  53. }
  54. }