Skip to content

Commit 7fbfb35

Browse files
author
Vadim Belov
committed
Improve Sentry user extraction from HTTP context claims
Enhanced UserFactory to prefer GUID user IDs, support multiple claim types for username and email, and default to "Anonymous" or empty values when claims are missing. This makes Sentry user identification more robust and flexible.
1 parent d6ffddb commit 7fbfb35

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

Sources/EasyExtensions.AspNetCore.Sentry/Factories/UserFactory.cs

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using EasyExtensions.AspNetCore.Extensions;
22
using Microsoft.AspNetCore.Http;
33
using Sentry;
4+
using System;
45
using System.Linq;
56
using System.Security.Claims;
67

@@ -21,13 +22,24 @@ public class UserFactory(IHttpContextAccessor httpContextAccessor) : ISentryUser
2122
{
2223
return null;
2324
}
25+
var context = httpContextAccessor.HttpContext;
26+
var claims = httpContextAccessor.HttpContext.User.Claims;
2427
int userId = httpContextAccessor.HttpContext.User.TryGetId();
28+
bool hasUserId = httpContextAccessor.HttpContext.User.TryGetUserId(out Guid guidUserId);
29+
string userIdStr = hasUserId ? guidUserId.ToString() : userId > 0 ? userId.ToString() : "Anonymous";
30+
string username = claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value
31+
?? claims.FirstOrDefault(x => x.Type == "preferred_username")?.Value
32+
?? "Anonymous";
33+
string email = claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value
34+
?? claims.FirstOrDefault(x => x.Type == "email")?.Value
35+
?? string.Empty;
36+
2537
return new SentryUser()
2638
{
27-
Id = userId.ToString(),
28-
IpAddress = httpContextAccessor.HttpContext.Request.GetRemoteAddress(),
29-
Username = httpContextAccessor.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value,
30-
Email = httpContextAccessor.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value,
39+
Id = userIdStr,
40+
IpAddress = context.Request.GetRemoteAddress(),
41+
Username = username,
42+
Email = email,
3143
};
3244
}
3345
}

0 commit comments

Comments
 (0)