簡體   English   中英

如何使用 Jnunit 5 從 Micronaut java 中的 HttpRequest 將值傳遞給 AuthenticationProvider

[英]How to pass the value to the AuthenticationProvider from HttpRequest in Micronaut java with Jnunit 5

使用 Micronaut HttpClient 執行 Junit 5 測試中的 HTTP 調用。

我正在嘗試使用 HttpRequest 將值傳遞給 AuthenticationProvider,如下所示

@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();
    }
}

這里我將屬性設置為request.setAttribute("fb_product", "owner"); 在身份驗證提供程序中,我正在嘗試訪問如下屬性

在此處輸入圖像描述

@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);
    }
}

在此處輸入圖像描述

該屬性未映射,這提供了一個 null 值var attributeValue = httpRequest.getAttribute("fb_product");

將數據從 HttpRequest 傳遞到 AuthenticationProvider 的最佳方法是什么

有一個token generator的概念,但是在security rule上有token generator,認證是null。

注入TokenGenerator並創建令牌

Map<String, Object> claims = new HashMap<>();
        claims.put("fb_product","owner");
        var claimGenerator = tokenGenerator.generateToken(claims);

要將 header 添加到請求中:

HttpRequest request = HttpRequest.POST("/product", new ProductModel())
        .bearerAuth(bearerAccessRefreshToken.getAccessToken())
        .header("fb_product", "owner");

要檢索 header:

Optional<String> fbOwner = request.getHeaders().findFirst("fb_owner");

您沒有在 HTTP 客戶端請求中設置屬性。

你想達到什么目的? 模擬正在登錄的用戶?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM