Skip to content

Commit d0b6acf

Browse files
committed
Add GetUserId and GetRequireUserId to resolve UserId from API Key or ClaimsPrincipal
1 parent 2f3d806 commit d0b6acf

2 files changed

Lines changed: 30 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#nullable enable
2+
using ServiceStack.Web;
3+
4+
namespace ServiceStack;
5+
6+
public static class ServerClaimUtils
7+
{
8+
/// <summary>
9+
/// Retrieves the User Id associated with the request from either API Key or ClaimsPrincipal.
10+
/// </summary>
11+
public static string? GetUserId(this IRequest? req)
12+
{
13+
var apiKeyUserId = req.GetApiKey()?.UserAuthId;
14+
if (apiKeyUserId != null)
15+
return apiKeyUserId;
16+
var user = req.GetClaimsPrincipal();
17+
return user.IsAuthenticated()
18+
? user.GetUserId()
19+
: null;
20+
}
21+
22+
/// <summary>
23+
/// Retrieves the required User Id associated with the request from either API Key or ClaimsPrincipal.
24+
/// Throws an unauthorized exception if the User Id is not available.
25+
/// </summary>
26+
public static string GetRequiredUserId(this IRequest? req) => req.GetUserId()
27+
?? throw HttpError.Unauthorized("User Authentication required");
28+
}

ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/AutoQueryTests.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -841,6 +841,8 @@ public async Task<object> Any(QueryMovies query)
841841
{
842842
using var db = AutoQuery.GetDb(query, base.Request);
843843
var q = AutoQuery.CreateQuery(query, base.Request, db);
844+
var userId = Request.GetClaimsPrincipal().GetUserId();
845+
q.Where(x => x.Rating == "PG-13");
844846
return await AutoQuery.ExecuteAsync(query, q, base.Request, db);
845847
}
846848
}

0 commit comments

Comments
 (0)