优化token代码

pull/10/head
刘鑫 4 months ago
parent 3a2c90460f
commit 12e4cf66fe
  1. 18
      WeiCloud.Fusion/AlarmService/Alarm.DomainService/DahAlarm/DahuaGeneralCtlService.cs
  2. 2
      WeiCloud.Fusion/Common.SharedService/Common.Shared.DomainService/DaHTokenService/ITokenProviderService.cs
  3. 38
      WeiCloud.Fusion/Common.SharedService/Common.Shared.DomainService/DaHTokenService/TokenProviderService.cs
  4. 2
      WeiCloud.Fusion/VideoService/Video.API/Controllers/DaHua/VideoManageController.cs
  5. 38
      WeiCloud.Fusion/VideoService/Video.DomainService/Dahvision/DahuaGeneralCtlService.cs

@ -121,6 +121,12 @@ namespace Alarm.DomainService.DahAlarm
var clientId = _configuration["DahuaAuth:ClientId"]; var clientId = _configuration["DahuaAuth:ClientId"];
var token = await _tokenProviderService.GetTokenAsync(clientId!); var token = await _tokenProviderService.GetTokenAsync(clientId!);
if (_tokenProviderService.IsTokenValid(token))
{
_logger.LogWarning("新增报警事件订阅:token无效");
return new DaHApiResult<object> { Success = false, Code = "1009", Msg = "token无效" };
}
// —— 发起请求 —— // —— 发起请求 ——
using var request = new HttpRequestMessage(HttpMethod.Post, url) using var request = new HttpRequestMessage(HttpMethod.Post, url)
{ {
@ -226,7 +232,11 @@ namespace Alarm.DomainService.DahAlarm
{ {
var clientId = _configuration["DahuaAuth:ClientId"]; var clientId = _configuration["DahuaAuth:ClientId"];
var token = await _tokenProviderService.GetTokenAsync(clientId!); var token = await _tokenProviderService.GetTokenAsync(clientId!);
if (_tokenProviderService.IsTokenValid(token))
{
_logger.LogWarning("取消订阅某个报警事件:token无效");
return false;
}
var url = $"https://{_configuration["DahuaAuth:Host"]}/evo-apigw/evo-event/1.0.0/subscribe/mqinfo?name={name}"; var url = $"https://{_configuration["DahuaAuth:Host"]}/evo-apigw/evo-event/1.0.0/subscribe/mqinfo?name={name}";
try try
@ -269,7 +279,11 @@ namespace Alarm.DomainService.DahAlarm
{ {
var clientId = _configuration["DahuaAuth:ClientId"]; var clientId = _configuration["DahuaAuth:ClientId"];
var token = await _tokenProviderService.GetTokenAsync(clientId!); var token = await _tokenProviderService.GetTokenAsync(clientId!);
if (_tokenProviderService.IsTokenValid(token))
{
_logger.LogWarning("获取事件列表:token无效");
return new DaHApiResult<SubscriptionMapDto> { Success = false, Code = "1009", Msg = "token无效" };
}
var url = $"https://{_configuration["DahuaAuth:Host"]}/evo-apigw/evo-event/1.0.0/subscribe/subscribe-list?monitorType=url&category={name}"; var url = $"https://{_configuration["DahuaAuth:Host"]}/evo-apigw/evo-event/1.0.0/subscribe/subscribe-list?monitorType=url&category={name}";
try try

@ -9,5 +9,7 @@ namespace Common.Shared.DomainService
public interface ITokenProviderService public interface ITokenProviderService
{ {
Task<string> GetTokenAsync(string clientId); Task<string> GetTokenAsync(string clientId);
bool IsTokenValid(string token);
} }
} }

@ -51,7 +51,8 @@ namespace Common.Shared.DomainService
} }
var refreshed = await TryRefreshOrLoginAsync(clientId, tokenEntry); var refreshed = await TryRefreshOrLoginAsync(clientId, tokenEntry);
return refreshed.AccessToken!;
return refreshed.AccessToken;
} }
finally finally
{ {
@ -98,9 +99,12 @@ namespace Common.Shared.DomainService
{ {
refreshed = await GetDaHToken(); refreshed = await GetDaHToken();
} }
if (refreshed != null && refreshed.AccessToken != "")
{
// 更新缓存 // 更新缓存
TokenCache.TokenMap[clientId] = refreshed; TokenCache.TokenMap[clientId] = refreshed;
}
return refreshed; return refreshed;
} }
catch (Exception ex) catch (Exception ex)
@ -118,10 +122,17 @@ namespace Common.Shared.DomainService
{ {
//1. 获取公钥 //1. 获取公钥
DaHApiResult<PublicKeyDto> publicKeyResult = await GetPublicKey(); DaHApiResult<PublicKeyDto> publicKeyResult = await GetPublicKey();
if (publicKeyResult.Success == false)
{
return new TokenEntry
{
AccessToken = string.Empty,
ExpireAt = DateTimeOffset.UtcNow.AddMinutes(1)
};
}
LoginRequestDto dto = new(); LoginRequestDto dto = new();
//2. 鉴权 //2. 鉴权
dto.PublicKey = publicKeyResult.Data.PublicKey; dto.PublicKey = publicKeyResult.Data!.PublicKey;
dto.ClientId = _configuration["DahuaAuth:ClientId"]!; dto.ClientId = _configuration["DahuaAuth:ClientId"]!;
dto.ClientSecret = _configuration["DahuaAuth:ClientSecret"]!; dto.ClientSecret = _configuration["DahuaAuth:ClientSecret"]!;
dto.Password = _configuration["DahuaAuth:Password"]!; dto.Password = _configuration["DahuaAuth:Password"]!;
@ -131,7 +142,7 @@ namespace Common.Shared.DomainService
TokenEntry refreshed = new() TokenEntry refreshed = new()
{ {
AccessToken = loginResult.Data.AccessToken, AccessToken = loginResult.Data!.AccessToken,
ExpireAt = DateTimeOffset.UtcNow.AddSeconds(120) ExpireAt = DateTimeOffset.UtcNow.AddSeconds(120)
}; };
return refreshed; return refreshed;
@ -271,7 +282,7 @@ namespace Common.Shared.DomainService
} }
result = tokenInfo!; result = tokenInfo!;
//固定的拼接方式 //固定的拼接方式
result.Data.AccessToken = string.Concat(tokenInfo?.Data.TokenType, " ", tokenInfo?.Data.AccessToken); result.Data!.AccessToken = string.Concat(tokenInfo?.Data!.TokenType, " ", tokenInfo?.Data!.AccessToken);
TokenEntry refreshed = new TokenEntry TokenEntry refreshed = new TokenEntry
{ {
@ -290,6 +301,21 @@ namespace Common.Shared.DomainService
return result; return result;
} }
/// <summary>
/// 判断token是否有效
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
public bool IsTokenValid(string token)
{
// 避免 NullReferenceException
if (string.IsNullOrWhiteSpace(token))
return true;
// 统一写法,后续改条件只改这里
return token.Length < 10;
}
#region RES加密 #region RES加密
private static string EncryptByPublicKey(string context, string publicKey) private static string EncryptByPublicKey(string context, string publicKey)

@ -145,7 +145,7 @@ namespace Video.API.Controllers.DaHua
/// </summary> /// </summary>
/// <param name="dto"></param> /// <param name="dto"></param>
/// <returns></returns> /// <returns></returns>
[HttpGet("download")] [HttpPost("download")]
public async Task<string> GetDownUrl(DownloadReqDto dto) public async Task<string> GetDownUrl(DownloadReqDto dto)
{ {
return await _rootVideoPlaybackService.Download(dto); return await _rootVideoPlaybackService.Download(dto);

@ -51,7 +51,11 @@ namespace Video.DomainService
// 2) Token:优先入参,其次缓存/获取(建议返回完整的 "Bearer xxx") // 2) Token:优先入参,其次缓存/获取(建议返回完整的 "Bearer xxx")
var clientId = _configuration["DahuaAuth:ClientId"]; var clientId = _configuration["DahuaAuth:ClientId"];
var token = await _tokenProviderService.GetTokenAsync(clientId!); var token = await _tokenProviderService.GetTokenAsync(clientId!);
if (_tokenProviderService.IsTokenValid(token))
{
_logger.LogWarning("hls等录像回放:token无效");
return new DaHApiResult<UrlDataDto> { Success = false, Code = "1009", Msg = "token无效" };
}
var url = $"https://{_configuration["DahuaAuth:Host"]}/evo-apigw/admin/API/video/stream/record"; var url = $"https://{_configuration["DahuaAuth:Host"]}/evo-apigw/admin/API/video/stream/record";
// 3) 构造请求(把 dto 放进 Body),并用 SendAsync 发送,才能带上头 // 3) 构造请求(把 dto 放进 Body),并用 SendAsync 发送,才能带上头
@ -103,7 +107,11 @@ namespace Video.DomainService
var clientId = _configuration["DahuaAuth:ClientId"]; var clientId = _configuration["DahuaAuth:ClientId"];
var token = await _tokenProviderService.GetTokenAsync(clientId!); var token = await _tokenProviderService.GetTokenAsync(clientId!);
if (_tokenProviderService.IsTokenValid(token))
{
_logger.LogWarning("查询普通录像信息列表:token无效");
return new DaHApiResult<RecordsResDto> { Success = false, Code = "1009", Msg = "token无效" };
}
var url = $"https://{_configuration["DahuaAuth:Host"]}/evo-apigw/admin/API/SS/Record/QueryRecords"; var url = $"https://{_configuration["DahuaAuth:Host"]}/evo-apigw/admin/API/SS/Record/QueryRecords";
using var req = new HttpRequestMessage(HttpMethod.Post, url) using var req = new HttpRequestMessage(HttpMethod.Post, url)
@ -156,6 +164,11 @@ namespace Video.DomainService
var clientId = _configuration["DahuaAuth:ClientId"]; var clientId = _configuration["DahuaAuth:ClientId"];
var token = await _tokenProviderService.GetTokenAsync(clientId!); var token = await _tokenProviderService.GetTokenAsync(clientId!);
if (_tokenProviderService.IsTokenValid(token))
{
_logger.LogWarning("通道分页查询失败:token无效");
return new DaHApiResult<PageInfoDto> { Success = false, Code = "1009", Msg = "token无效" };
}
var url = $"https://{_configuration["DahuaAuth:Host"]}/evo-apigw/evo-brm/1.2.0/device/channel/subsystem/page"; var url = $"https://{_configuration["DahuaAuth:Host"]}/evo-apigw/evo-brm/1.2.0/device/channel/subsystem/page";
@ -212,6 +225,11 @@ namespace Video.DomainService
// 2) Token:优先用入参;否则走缓存/获取(建议返回已带前缀的 "Bearer xxx") // 2) Token:优先用入参;否则走缓存/获取(建议返回已带前缀的 "Bearer xxx")
var clientId = _configuration["DahuaAuth:ClientId"]; var clientId = _configuration["DahuaAuth:ClientId"];
var token = await _tokenProviderService.GetTokenAsync(clientId!); var token = await _tokenProviderService.GetTokenAsync(clientId!);
if (_tokenProviderService.IsTokenValid(token))
{
_logger.LogWarning(" HLS实时流请求失败:token无效");
return new DaHApiResult<UrlDataDto> { Success = false, Code = "1009", Msg = "token无效" };
}
var url = $"https://{_configuration["DahuaAuth:Host"]}/evo-apigw/admin/API/video/stream/realtime"; var url = $"https://{_configuration["DahuaAuth:Host"]}/evo-apigw/admin/API/video/stream/realtime";
@ -317,6 +335,11 @@ namespace Video.DomainService
// 先用缓存里的 token,不足5分钟过期再刷新(按你之前的口径来) // 先用缓存里的 token,不足5分钟过期再刷新(按你之前的口径来)
var clientId = _configuration["DahuaAuth:ClientId"]; var clientId = _configuration["DahuaAuth:ClientId"];
var token = await _tokenProviderService.GetTokenAsync(clientId!); var token = await _tokenProviderService.GetTokenAsync(clientId!);
if (_tokenProviderService.IsTokenValid(token))
{
_logger.LogWarning("rtsp录像回放:token无效");
return new DaHApiResult<UrlDataDto> { Success = false, Code = "1009", Msg = "token无效" };
}
var url = $"https://{_configuration["DahuaAuth:Host"]}/evo-apigw/admin/API/SS/Playback/StartPlaybackByTime"; var url = $"https://{_configuration["DahuaAuth:Host"]}/evo-apigw/admin/API/SS/Playback/StartPlaybackByTime";
@ -370,6 +393,11 @@ namespace Video.DomainService
var clientId = _configuration["DahuaAuth:ClientId"]; var clientId = _configuration["DahuaAuth:ClientId"];
var token = await _tokenProviderService.GetTokenAsync(clientId!); var token = await _tokenProviderService.GetTokenAsync(clientId!);
if (_tokenProviderService.IsTokenValid(token))
{
_logger.LogWarning("rtsp实时预览接口方式:token无效");
return new DaHApiResult<UrlDataDto> { Success = false, Code = "1009", Msg = "token无效" };
}
var url = $"https://{_configuration["DahuaAuth:Host"]}/evo-apigw/admin/API/MTS/Video/StartVideo"; var url = $"https://{_configuration["DahuaAuth:Host"]}/evo-apigw/admin/API/MTS/Video/StartVideo";
@ -416,6 +444,12 @@ namespace Video.DomainService
{ {
var clientId = _configuration["DahuaAuth:ClientId"]; var clientId = _configuration["DahuaAuth:ClientId"];
var token = await _tokenProviderService.GetTokenAsync(clientId!); var token = await _tokenProviderService.GetTokenAsync(clientId!);
if (_tokenProviderService.IsTokenValid(token))
{
_logger.LogWarning("下载:token无效");
return "下载地址无效";
}
return _configuration["DahuaAuth:Host"] + $"/evo-apigw/evo-httpnode/vod/cam/download.mp4?vcuid={dto.Vcuid}&subtype={dto.Subtype}&starttime={dto.StartTime}endtime={dto.EndTime}&videoType={dto.VideoType}&token={token}&recordType={dto.RecordType}"; return _configuration["DahuaAuth:Host"] + $"/evo-apigw/evo-httpnode/vod/cam/download.mp4?vcuid={dto.Vcuid}&subtype={dto.Subtype}&starttime={dto.StartTime}endtime={dto.EndTime}&videoType={dto.VideoType}&token={token}&recordType={dto.RecordType}";
} }
} }

Loading…
Cancel
Save