VSession.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using Microsoft.AspNetCore.Http;
  2. using System;
  3. using VCommon.Ioc;
  4. using VCommon.VApplication;
  5. namespace VCommon.VOpenApi.VAspNetCore
  6. {
  7. public class VSession : IVSession, ISingletonIocClass
  8. {
  9. private const string AuthorizationHeader = "Authorization";
  10. private const string TokenHeaderPart = "Token";
  11. private readonly HttpContext _context;
  12. private readonly IUserTokenStore _tokenStore;
  13. private bool _isTokenChecked;
  14. private Guid? _tenantId;
  15. private Guid? _userId;
  16. internal VSession(HttpContext context, IUserTokenStore tokenStore)
  17. {
  18. _context = context;
  19. _tokenStore = tokenStore;
  20. }
  21. private void EnsureTokenCheck()
  22. {
  23. if (_isTokenChecked) return;
  24. string token = null;
  25. //从请求头获取 Token
  26. string rawToken;
  27. if (false == string.IsNullOrWhiteSpace(rawToken = _context.Request.Headers[AuthorizationHeader]))
  28. {
  29. var parts = rawToken.Split(' ');
  30. if (parts.Length == 2 && parts[0] == TokenHeaderPart && false == string.IsNullOrWhiteSpace(parts[1]))
  31. {
  32. token = parts[1];
  33. }
  34. }
  35. //验证Token
  36. if (null != token) _tokenStore.Validate(token, out _tenantId, out _userId);
  37. _isTokenChecked = true;
  38. }
  39. public Guid? UserId
  40. {
  41. get
  42. {
  43. EnsureTokenCheck();
  44. return _userId;
  45. }
  46. }
  47. public Guid? TenantId
  48. {
  49. get
  50. {
  51. EnsureTokenCheck();
  52. return _tenantId;
  53. }
  54. }
  55. public void DemandAuth()
  56. {
  57. EnsureTokenCheck();
  58. if (false == UserId.HasValue) throw new VApplicationAuthException("需要验证身份", AuthReason.AuthRequired);
  59. }
  60. }
  61. }