Skip to content

Commit

Permalink
don't need to configure jwt secret key
Browse files Browse the repository at this point in the history
  • Loading branch information
sdcb committed Jan 20, 2025
1 parent 810837b commit 1ab433a
Show file tree
Hide file tree
Showing 7 changed files with 23 additions and 38 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Chats.BE.Controllers.Admin.GlobalConfigs.Dtos;
using Chats.BE.Controllers.Common;
using Chats.BE.DB;
using Chats.BE.Services.Configs;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
Expand Down
3 changes: 0 additions & 3 deletions src/BE/DB/Init/InitService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,6 @@ public async Task Init(CancellationToken cancellationToken = default)

private static async Task InsertInitialData(IServiceScope scope, ChatsDB db, CancellationToken cancellationToken)
{
JwtKeyManager jwtKeyManager = scope.ServiceProvider.GetRequiredService<JwtKeyManager>();
await jwtKeyManager.GetOrCreateSecretKey(cancellationToken);

BasicData.InsertAll(db);
await db.SaveChangesAsync(cancellationToken);

Expand Down
2 changes: 1 addition & 1 deletion src/BE/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public static async Task Main(string[] args)
builder.Services.AddSingleton<CsrfTokenService>();
builder.Services.AddScoped<GlobalDBConfig>();
builder.Services.AddScoped<UserManager>();
builder.Services.AddScoped<JwtKeyManager>();
builder.Services.AddSingleton<JwtKeyManager>();
builder.Services.AddScoped<SessionManager>();
builder.Services.AddScoped<UserModelManager>();
builder.Services.AddScoped<OpenAIApiKeySessionManager>();
Expand Down
2 changes: 0 additions & 2 deletions src/BE/Services/Configs/DBConfigKey.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

public static class DBConfigKey
{
public const string JwtSecretKey = "JwtSecretKey";

public const string TencentSms = "tencentSms";

public const string SiteInfo = "siteInfo";
Expand Down
35 changes: 13 additions & 22 deletions src/BE/Services/Sessions/JwtKeyManager.cs
Original file line number Diff line number Diff line change
@@ -1,28 +1,19 @@
using Chats.BE.DB;
using Chats.BE.Services.Configs;
using Microsoft.EntityFrameworkCore;
namespace Chats.BE.Services.Sessions;

namespace Chats.BE.Services.Sessions;

public class JwtKeyManager(ChatsDB db)
public class JwtKeyManager
{
public async Task<string> GetOrCreateSecretKey(CancellationToken cancellationToken)
public string GetOrCreateSecretKey()
{
// check environment variable first
// if it's not set, then generate a new one and store into database
string? secretKey = Environment.GetEnvironmentVariable("JWT_SECRET_KEY");
if (secretKey != null) return secretKey;

string? configText = await db.Configs
.Where(s => s.Key == DBConfigKey.JwtSecretKey)
.Select(x => x.Value)
.SingleOrDefaultAsync(cancellationToken);
if (configText != null) return configText;

string generated = Guid.NewGuid().ToString();
db.Configs.Add(new Config { Key = DBConfigKey.JwtSecretKey, Value = generated, Description = $"Generated at {DateTime.Now:O}" });
await db.SaveChangesAsync(cancellationToken);

return generated;
if (secretKey != null)
{
return secretKey;
}
else
{
string generated = Guid.NewGuid().ToString();
Environment.SetEnvironmentVariable("JWT_SECRET_KEY", generated);
return generated;
}
}
}
16 changes: 8 additions & 8 deletions src/BE/Services/Sessions/SessionManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ public class SessionManager(JwtKeyManager jwtKeyManager)
private const string ValidAudience = "chats";
private static readonly TimeSpan ValidPeriod = TimeSpan.FromHours(8);

public async Task<SessionEntry> GetCachedUserInfoBySession(string jwt, CancellationToken cancellationToken = default)
public Task<SessionEntry> GetCachedUserInfoBySession(string jwt, CancellationToken _ = default)
{
ClaimsPrincipal claims = ValidateJwt(jwt, await GetSecurityKey(cancellationToken));
return SessionEntry.FromClaims(claims);
ClaimsPrincipal claims = ValidateJwt(jwt, GetSecurityKey());
return Task.FromResult(SessionEntry.FromClaims(claims));
}

private static ClaimsPrincipal ValidateJwt(string jwt, SecurityKey signingKey)
Expand Down Expand Up @@ -51,11 +51,11 @@ internal static byte[] Pdkdf2StringToByte32(string input)
return new Rfc2898DeriveBytes(input, salt, 10000, HashAlgorithmName.SHA256).GetBytes(32);
}

private async Task<SymmetricSecurityKey> GetSecurityKey(CancellationToken cancellationToken) => new(Pdkdf2StringToByte32(await jwtKeyManager.GetOrCreateSecretKey(cancellationToken)));
private SymmetricSecurityKey GetSecurityKey() => new(Pdkdf2StringToByte32(jwtKeyManager.GetOrCreateSecretKey()));

public async Task<LoginResponse> GenerateSessionForUser(User user, CancellationToken cancellationToken)
public Task<LoginResponse> GenerateSessionForUser(User user, CancellationToken _)
{
SigningCredentials cred = new(await GetSecurityKey(cancellationToken), SecurityAlgorithms.HmacSha256);
SigningCredentials cred = new(GetSecurityKey(), SecurityAlgorithms.HmacSha256);
SessionEntry sessionEntry = new()
{
UserId = user.Id,
Expand All @@ -73,12 +73,12 @@ public async Task<LoginResponse> GenerateSessionForUser(User user, CancellationT

string jwt = new JwtSecurityTokenHandler().WriteToken(token);
bool hasPayService = false;
return new LoginResponse
return Task.FromResult(new LoginResponse
{
SessionId = jwt,
UserName = user.DisplayName,
Role = user.Role,
CanReCharge = hasPayService,
};
});
}
}
2 changes: 0 additions & 2 deletions src/FE/types/config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
export enum GlobalConfigKeys {
tencentSms = 'tencentSms',
siteInfo = 'siteInfo',
JwtSecretKey = 'JwtSecretKey',
}

export interface SiteInfoConfig {
Expand All @@ -21,5 +20,4 @@ export const GlobalDefaultConfigs = {
filingNumber: '',
companyName: '',
},
JwtSecretKey: '',
};

0 comments on commit 1ab433a

Please sign in to comment.