1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- using Microsoft.AspNetCore.Http;
- using System;
- using VCommon.Ioc;
- using VCommon.VApplication;
- namespace VCommon.VOpenApi.VAspNetCore
- {
- public class VSession : IVSession, ISingletonIocClass
- {
- private const string AuthorizationHeader = "Authorization";
- private const string TokenHeaderPart = "Token";
- private readonly HttpContext _context;
- private readonly IUserTokenStore _tokenStore;
- private bool _isTokenChecked;
- private Guid? _tenantId;
- private Guid? _userId;
- internal VSession(HttpContext context, IUserTokenStore tokenStore)
- {
- _context = context;
- _tokenStore = tokenStore;
- }
- private void EnsureTokenCheck()
- {
- if (_isTokenChecked) return;
- string token = null;
- //从请求头获取 Token
- string rawToken;
- if (false == string.IsNullOrWhiteSpace(rawToken = _context.Request.Headers[AuthorizationHeader]))
- {
- var parts = rawToken.Split(' ');
- if (parts.Length == 2 && parts[0] == TokenHeaderPart && false == string.IsNullOrWhiteSpace(parts[1]))
- {
- token = parts[1];
- }
- }
- //验证Token
- if (null != token) _tokenStore.Validate(token, out _tenantId, out _userId);
- _isTokenChecked = true;
- }
- public Guid? UserId
- {
- get
- {
- EnsureTokenCheck();
- return _userId;
- }
- }
- public Guid? TenantId
- {
- get
- {
- EnsureTokenCheck();
- return _tenantId;
- }
- }
- public void DemandAuth()
- {
- EnsureTokenCheck();
- if (false == UserId.HasValue) throw new VApplicationAuthException("需要验证身份", AuthReason.AuthRequired);
- }
- }
- }
|