Skip to content

Commit

Permalink
Call PopulateFromClaims() from IdentityJwtAuthProvider populated bear…
Browse files Browse the repository at this point in the history
…er tokens
  • Loading branch information
mythz committed Apr 29, 2024
1 parent 71be0cd commit a5338be
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 16 deletions.
Expand Up @@ -310,10 +310,7 @@ public override bool IsAuthorized(IAuthSession session, IAuthTokens tokens, Auth
var principal = new JwtSecurityTokenHandler().ValidateToken(bearerToken,
Options!.TokenValidationParameters, out SecurityToken validatedToken);

var jwtToken = (JwtSecurityToken)validatedToken;
var claims = jwtToken.Claims.ToList();

var jwtSession = CreateSessionFromClaims(req, claims);
var jwtSession = CreateSessionFromClaims(req, principal);
var to = jwtSession.ConvertTo<AuthenticateResponse>();
to.UserId = jwtSession.UserAuthId;
return (to as object).InTask();
Expand All @@ -331,21 +328,13 @@ public Task PreAuthenticateAsync(IRequest req, IResponse res)
if (!string.IsNullOrEmpty(token) &&
!(req.Items.TryGetValue(Keywords.Session, out var oSession) && oSession is IAuthSession { IsAuthenticated: true }))
{
List<Claim> claims;
var user = req.GetClaimsPrincipal();
if (user.IsAuthenticated())
{
claims = user.Claims.ToList();
}
else
if (!user.IsAuthenticated())
{
var principal = new JwtSecurityTokenHandler().ValidateToken(token,
user = new JwtSecurityTokenHandler().ValidateToken(token,
Options!.TokenValidationParameters, out SecurityToken validatedToken);

var jwtToken = (JwtSecurityToken)validatedToken;
claims = jwtToken.Claims.ToList();
}
var session = CreateSessionFromClaims(req, claims);
var session = CreateSessionFromClaims(req, user);
req.Items[Keywords.Session] = session;
}
return Task.CompletedTask;
Expand Down Expand Up @@ -410,8 +399,9 @@ public async Task MessageReceivedAsync(MessageReceivedContext ctx)
}
}

public virtual IAuthSession CreateSessionFromClaims(IRequest req, List<Claim> claims)
public virtual IAuthSession CreateSessionFromClaims(IRequest req, ClaimsPrincipal principal)
{
var claims = principal.Claims.ToList();
var sessionId = claims.FirstOrDefault(x => x.Type == "jid")?.Value ?? HostContext.AppHost.CreateSessionId();
var session = SessionFeature.CreateNewSession(req, sessionId);

Expand All @@ -423,6 +413,8 @@ public virtual IAuthSession CreateSessionFromClaims(IRequest req, List<Claim> cl
claims.Each(x => claimMap.Add(new(x.Type, x.Value)));
session.PopulateFromMap(claimMap);

(session as IAuthSessionExtended)?.PopulateFromClaims(req, principal);

OnSessionCreated?.Invoke(session, claims, req);

HostContext.AppHost.OnSessionFilter(req, session, sessionId);
Expand Down
Expand Up @@ -20,6 +20,7 @@
using NUnit.Framework;
using ServiceStack.Auth;
using ServiceStack.Data;
using ServiceStack.Messaging;
using ServiceStack.OrmLite;
using ServiceStack.Text;
using ServiceStack.Web;
Expand Down Expand Up @@ -58,6 +59,22 @@ public class Roles
public const string Employee = nameof(Employee);
}

[ValidateIsAuthenticated]
public class MqBearerToken : IHasBearerToken, IReturn<MqBearerToken>
{
public int Id { get; set; }
public string? BearerToken { get; set; }
}

public class BackgroundAuthServices : Service
{
public object Any(MqBearerToken request)
{
request.Id++;
return request;
}
}

public class IdentityJwtAuthProviderTests
{
private static readonly int TotalRockstars = AutoQueryAppHost.SeedRockstars.Length;
Expand Down Expand Up @@ -166,6 +183,10 @@ public override void Configure()
log.LogInformation("Seeding Database...");
using var db = GetDbConnection();
AutoQueryAppHost.SeedDatabase(db);

var mqService = Resolve<IMessageService>();
mqService.RegisterHandler<MqBearerToken>(ExecuteMessage);
mqService.Start();
}
}

Expand Down Expand Up @@ -245,6 +266,8 @@ public IdentityJwtAuthProviderTests()
});
});

services.AddSingleton<IMessageService>(c => new BackgroundMqService());

var app = builder.Build();

app.UseAuthorization();
Expand Down Expand Up @@ -275,6 +298,18 @@ private async Task<string> CreateExpiredTokenAsync()
return jwt;
}

private async Task<string> GetBearerTokenAsync()
{
var authClient = GetClient();
var response = await authClient.SendAsync(new Authenticate
{
provider = "credentials",
UserName = Username,
Password = Password,
});
return authClient.GetTokenCookie();
}

private async Task<string> GetRefreshTokenAsync()
{
var authClient = GetClient();
Expand Down Expand Up @@ -425,6 +460,17 @@ public async Task Endpoints_Can_Auto_reconnect_with_RefreshToken_after_expired_t
response = await client.SendAsync(request);
Assert.That(response.Result, Is.EqualTo("Hello, test"));
}

[Test]
public async Task Can_authenticate_with_BearerToken_in_MQ()
{
var bearerToken = await GetBearerTokenAsync();

await ServiceStackHost.Instance.ExecuteMessageAsync(new Message<MqBearerToken>(new MqBearerToken
{
BearerToken = bearerToken,
}));
}
}

#endif

0 comments on commit a5338be

Please sign in to comment.