Using Micronaut HttpClient to perform the HTTP calls in Junit 5 testing.
I am trying to pass the value to AuthenticationProvider using HttpRequest as below
@MicronautTest
public class ProductCreateTest extends TestContainerFixture {
@Inject
@Client("/")
HttpClient client;
@Test
@DisplayName("Should create the product")
void shouldCreateTheProduct() {
HttpRequest request = HttpRequest.POST("/product", new ProductModel())
.bearerAuth(bearerAccessRefreshToken.getAccessToken());
request.setAttribute("fb_product", "owner");
HttpResponse < ProductModel > rsp = client.toBlocking().exchange(request, ProductModel.class);
var item = rsp.body();
}
}
Here I am setting an attribute as request.setAttribute("fb_product", "owner");
and in the authentication provider I am trying to access the attribute as below
@Singleton
@Requires(env = Environment.TEST)
public record AuthenticationProviderFixture(Configuration configuration) implements AuthenticationProvider {
@Override
public Publisher<AuthenticationResponse> authenticate(HttpRequest<?> httpRequest, AuthenticationRequest<?, ?> authenticationRequest) {
return Flux.create(emitter -> {
if (authenticationRequest.getIdentity().equals(configuration.Username()) && authenticationRequest.getSecret().equals(configuration.Password())) {
var attributeValue = httpRequest.getAttribute("fb_product");
HashMap<String, Object> attributes = new HashMap<>();
emitter.next(AuthenticationResponse.success((String) authenticationRequest.getIdentity(), attributes));
emitter.complete();
} else {
emitter.error(AuthenticationResponse.exception());
}
}, FluxSink.OverflowStrategy.ERROR);
}
}
The attribute is not mapped and this provides an null value var attributeValue = httpRequest.getAttribute("fb_product");
What is the best approach to pass the data from HttpRequest to AuthenticationProvider
There is a concept of the token generator, however, with the token generator on the security rule, the authentication is null.
Inject the TokenGenerator
and create a token
Map<String, Object> claims = new HashMap<>();
claims.put("fb_product","owner");
var claimGenerator = tokenGenerator.generateToken(claims);
To add a header to the request:
HttpRequest request = HttpRequest.POST("/product", new ProductModel())
.bearerAuth(bearerAccessRefreshToken.getAccessToken())
.header("fb_product", "owner");
To retrieve the header:
Optional<String> fbOwner = request.getHeaders().findFirst("fb_owner");