Skip to content

Commit 778ec57

Browse files
author
fdonnet
committed
Add token encrypt decrypt in cache.
1 parent 1648128 commit 778ec57

File tree

5 files changed

+50
-2
lines changed

5 files changed

+50
-2
lines changed

UbikLink.AppHost/Program.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
var rabbitUser = builder.AddParameter("rabbit-username", secret: true);
1717
var rabbitPassword = builder.AddParameter("rabbit-password", secret: true);
1818
var transportType = builder.AddParameter("transport-type", secret: false);
19+
var authTokenStoreKey = builder.AddParameter("auth-token-store-key", secret: true);
1920

2021
//Postgres (local)
2122
var db = builder.AddPostgres("ubiklink-postgres", postgresUsername, postgresPassword)
@@ -95,6 +96,7 @@
9596
.WithEnvironment("AuthConfig__TokenUrl", authTokenUrl)
9697
.WithEnvironment("AuthConfig__ClientId", securityClientAppId)
9798
.WithEnvironment("AuthConfig__ClientSecret", securityClientAppSecret)
99+
.WithEnvironment("AuthConfig__AuthTokenStoreKey", securityClientAppSecret)
98100
.WithEnvironment("Messaging__Transport", transportType)
99101
.WithEnvironment("Messaging__RabbitUser", rabbitUser)
100102
.WithEnvironment("Messaging__RabbitPassword", rabbitPassword);

UbikLink.AppHost/appsettings.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,5 +31,6 @@
3131
"Parameters:auth-metadata-url": "http://localhost:8080/realms/ubik/.well-known/openid-configuration",
3232
"Parameters:auth-base-url": "http://localhost:8080/realms/ubik",
3333
"ConnectionStrings:messaging": "xx",
34-
"Parameters:keycloak-password": "admin"
34+
"Parameters:keycloak-password": "admin",
35+
"Parameters:auth-token-store-key": "Ye6Y36ocA4SaGqYzd0HgmqMhVaM2jlkE"
3536
}

UbikLink.Common/Auth/AuthConfigOptions.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,5 +24,6 @@ public class AuthConfigOptions
2424
public List<string> Scopes { get; set; } = default!;
2525
public bool AuthorizeBadCert { get; set; } = false;
2626
public string AuthTokenHttpClientName { get; set; } = "default";
27+
public string AuthTokenStoreKey { get; set; } = "default";
2728
}
2829
}

UbikLink.Common/Frontend/Auth/UserAndTokenCache.cs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
using Microsoft.Extensions.Caching.Hybrid;
33
using Microsoft.Extensions.Options;
44
using System.IdentityModel.Tokens.Jwt;
5+
using System.Security.Cryptography;
6+
using System.Text;
57
using UbikLink.Common.Auth;
68
using UbikLink.Security.Contracts.Users.Results;
79

@@ -20,6 +22,8 @@ public async Task RemoveUserTokenAsync(string key)
2022

2123
public async Task SetUserTokenAsync(TokenCacheEntry token)
2224
{
25+
token.AccessToken = Encrypt(token.AccessToken, _authOptions.AuthTokenStoreKey);
26+
token.RefreshToken = Encrypt(token.RefreshToken, _authOptions.AuthTokenStoreKey);
2327
await cache.SetAsync($"{_authOptions.ClientAppName}_{token.UserId}", token, new HybridCacheEntryOptions()
2428
{
2529
Expiration = TimeSpan.FromMinutes(_authOptions.RefreshTokenExpTimeInMinutes + 1),
@@ -36,6 +40,8 @@ public async Task SetUserTokenAsync(TokenCacheEntry token)
3640

3741
if (token == null) return null;
3842

43+
token.AccessToken = Decrypt(token.AccessToken, _authOptions.AuthTokenStoreKey);
44+
token.RefreshToken = Decrypt(token.RefreshToken, _authOptions.AuthTokenStoreKey);
3945
token = await RefreshTokenAsync(token, userId);
4046

4147
return token;
@@ -139,5 +145,42 @@ private Dictionary<string, string> ValuesForRefresh(string token)
139145
{ "grant_type", "refresh_token" },
140146
};
141147
}
148+
149+
public static string Encrypt(string plainText, string key)
150+
{
151+
using Aes aesAlg = Aes.Create();
152+
aesAlg.Key = Encoding.UTF8.GetBytes(key);
153+
aesAlg.GenerateIV();
154+
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
155+
156+
using MemoryStream msEncrypt = new();
157+
msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
158+
using (CryptoStream csEncrypt = new(msEncrypt, encryptor, CryptoStreamMode.Write))
159+
using (StreamWriter swEncrypt = new(csEncrypt))
160+
{
161+
swEncrypt.Write(plainText);
162+
}
163+
return Convert.ToBase64String(msEncrypt.ToArray());
164+
}
165+
166+
public static string Decrypt(string cipherText, string key)
167+
{
168+
byte[] fullCipher = Convert.FromBase64String(cipherText);
169+
using Aes aesAlg = Aes.Create();
170+
aesAlg.Key = Encoding.UTF8.GetBytes(key);
171+
byte[] iv = new byte[aesAlg.BlockSize / 8];
172+
byte[] cipher = new byte[fullCipher.Length - iv.Length];
173+
174+
Array.Copy(fullCipher, iv, iv.Length);
175+
Array.Copy(fullCipher, iv.Length, cipher, 0, cipher.Length);
176+
177+
aesAlg.IV = iv;
178+
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
179+
180+
using MemoryStream msDecrypt = new(cipher);
181+
using CryptoStream csDecrypt = new(msDecrypt, decryptor, CryptoStreamMode.Read);
182+
using StreamReader srDecrypt = new(csDecrypt);
183+
return srDecrypt.ReadToEnd();
184+
}
142185
}
143186
}

UbikLink.Security.UI/appsettings.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
"ClientAppName": "Security.UI.App",
2323
"Scopes": [ "openid", "offline_access" ],
2424
"AuthorizeBadCert": false,
25-
"AuthTokenHttpClientName": "security-httpclient"
25+
"AuthTokenHttpClientName": "security-httpclient",
26+
"AuthTokenStoreKey": "Xxxxxxx"
2627
}
2728
}

0 commit comments

Comments
 (0)