Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/BiSheng.Server/Auth/ApiKeyAuthHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,21 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
return AuthenticateResult.Fail("Invalid or inactive API key.");
}

// 节流更新 LastUsedAt,避免每次请求都写库
var now = DateTime.UtcNow;
if (key.LastUsedAt is null || now - key.LastUsedAt.Value > TimeSpan.FromMinutes(5))
{
key.LastUsedAt = now;
try
{
await db.SaveChangesAsync();
}
catch (Exception ex)
{
Logger.LogDebug(ex, "更新 ApiKey.LastUsedAt 失败(不影响认证)");
}
}

var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, key.UserId.ToString()),
Expand Down
3 changes: 3 additions & 0 deletions src/BiSheng.Server/Data/Entities/ApiKey.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ public class ApiKey

public DateTime CreatedAt { get; set; } = DateTime.UtcNow;

/// <summary>最近一次成功通过此 Key 认证的时间(UTC);未使用过为 null</summary>
public DateTime? LastUsedAt { get; set; }

// Navigation
[ForeignKey(nameof(UserId))]
public User User { get; set; } = null!;
Expand Down
Loading
Loading