HttpContext RequestServices is null
marcindruzgala opened this issue · 3 comments
Hello :)
So we are using albo for our integration tests but I'm recently fighting with something and I can't figure out what I'm doing wrong. So, we have very simple set up of the AlboHost
var albaHost = Alba.AlbaHost.ForStartup<Startup>(builder =>
{
builder.UseEnvironment("local");
builder.UseSerilogDefaults();
builder.ConfigureAppConfiguration((_, config) =>
{
config.AddInMemoryCollection(LoadAppSettings());
});
return builder;
});
Since we're using Identity Server and some of our endpoints are protected by bearer tokens I wanted to generate those and add them to the request, it looks more or less like this:
public static void ConfigureJwt(this HttpContext context,
User user,
string? clientId = null,
IEnumerable<string>? scopes = null,
IEnumerable<string>? audiences = null)
{
var identityServerTools = context.RequestServices.GetRequiredService<IdentityServerTools>();
// async call in sync function, have to await it in ugly way
var jwt = identityServerTools.IssueClientJwtAsync(clientId, 60, scopes, audiences).GetAwaiter().GetResult();
context.SetBearerToken(jwt);
}
That I later call in our test like this:
await Host.Scenario(s =>
{
s.ConfigureHttpContext(c =>
{
c.ConfigureJwt(user);
});
But it crashes with NRE on context.RequestServices.GetRequiredService
.
I've tried to 'fix it' by calling BeforeEach
on AlbaHost and assigning RequestServices
like below but it only helped with NRE 🤔
AlbaHost.BeforeEach(c =>
{
c.RequestServices = AlbaHost.Services.CreateScope().ServiceProvider;
});
This removes the NRE but then IdentityServerTools
internally uses IHttpContextAccessor
and HttpContext
property on that object is null :/
Any ideas what I'm doing wrong?
I'll investigate this at some point, but I'd recommend using the security extensions that will stub out authentication within the Alba project:
https://jasperfx.github.io/alba/guide/security.html
Man, so sorry it took so long to look into this. I have no idea why the IAlbaHost.Services would be null unless something went wrong with bootstrapping and it failed silently somehow.
But what @Hawxy said.
Closing this as stale.