ReactiveFeignClient - how to propagate headers from controller to client without auth - reactive-programming

I received X-Forwarded-Host and X-Forwarded-Proto in my controller endpoints, and the endpoint has a reactive pipeline to call a ReactiveFeignClient class.
These headers should be propagated to my client requests, but as I see it, it has not. I have no Principal in this pipeline, because the endpoints needs no auth, so I cannot use ReactiveSecurityContextHolder.withAuthentication(user)
I already added a WebFilter to read headers from request:
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return chain.filter(exchange).subscriberContext((context) -> {
ServerHttpRequest request = exchange.getRequest();
Map<String, String> headers = (Map)request.getHeaders().toSingleValueMap().entrySet().stream().filter((entry) -> {
return ((String)entry.getKey()).equalsIgnoreCase(this.authLibConfig.getXForwardedHostHeader()) || ((String)entry.getKey()).equalsIgnoreCase(this.authLibConfig.getXForwardedProtoHeader());
}).collect(Collectors.toMap(Entry::getKey, Entry::getValue));
System.out.println("Adding all headers now: ");
context.put("headers_to_propagate", headers);
return context;
});
}
But I don't know where in the config of client can I retrieve them from the Context and put into requests in client.
Now I do this:(
#Bean
public ReactiveHttpRequestInterceptor forwardingHeadersInterceptor(ReactiveFeignUtils reactiveFeignUtils) {
return reactiveFeignUtils::mutateRequestHeadersForNoAuthRequests;
}
And:
public Mono<ReactiveHttpRequest> mutateRequestHeadersForNoAuthRequests(ReactiveHttpRequest reactiveHttpRequest) {
return Mono.subscriberContext().doOnNext((context) -> {
System.out.println("Current context: " + context.toString());
if (context.hasKey("headers_to_propagate")) {
System.out.println("Getting all host headers: ");
reactiveHttpRequest.headers().putAll((Map)context.get("headers_to_propagate"));
}
}).thenReturn(reactiveHttpRequest);
}
But no headers are forwarded.

I ended up creating a customized class implementing Authentication and add these fields as metadata property to it; because even though this endpoint requires no auth, headers related to member id and other auth info are received, so I can construct an Authentication principal.
Actually as I see, working with this object is the only way.

Related

Token mismatch exception when deploying in any VM

Here is my csrf and cors handler of my vertx application
#Log4j2
public class CsrfVerticle extends AbstractVerticle {
private final Set<HttpMethod> httpMethodSet =
new HashSet<>(Arrays.asList(GET, POST, OPTIONS, PUT, DELETE, HEAD));
private final Set<String> headerSet = new HashSet<>(
Arrays.asList("Content-Type", "Authorization", "Origin", "Accept", "X-Requested-With",
"Cookie", "X-XSRF-TOKEN"));
private Connection dbConnection;
private WebClient webClient;
private Vertx vertx;
public void start() throws Exception {
super.start();
HttpServer httpServer = TestService.vertx.createHttpServer();
Router router = Router.router(TestService.vertx);
SessionStore store = LocalSessionStore.create(vertx);
SessionHandler sessionHandler = SessionHandler.create(store)
.setCookieSameSite(CookieSameSite.STRICT)
.setCookieHttpOnlyFlag(false);
router.route().handler(LoggerHandler.create());
if (TestService.serviceConfiguration.isEnableCSRF()) {
router.route()
.handler(CorsHandler.create("*").allowedMethods(httpMethodSet).allowedHeaders(headerSet)
.allowCredentials(true).addOrigin(TestService.serviceConfiguration.getFrontendUrl()));
router.route().handler(
CSRFHandler.create(vertx, csrfSecret()).setCookieHttpOnly(false))
.handler(sessionHandler);
} else {
router.route()
.handler(CorsHandler.create("*").allowedMethods(httpMethodSet).allowedHeaders(headerSet)
.allowCredentials(true)).handler(sessionHandler);
}
dbConnection = createConnection(TestService.serviceConfiguration.getJdbcConfig());
TestAuth testAuth = new TestAuth(TestService.serviceConfiguration.getUsername(),
TestService.serviceConfiguration.getPassword());
AuthenticationHandler basicAuthHandler = BasicAuthHandler.create(testAuth);
router.route("/student/*").handler(basicAuthHandler);
router.route("/student/add").method(HttpMethod.POST).handler(this::handleAddUser);
router.route("/student/get").method(HttpMethod.GET).handler(this::handleGetUser);
router.route("/student/delete").method(HttpMethod.DELETE)
.handler(this::handleDeleteUser);
router.route("/student/update").method(HttpMethod.PUT).handler(this::handleUpdateUser);
httpServer.requestHandler(router).listen(TestService.serviceConfiguration.getPort());
log.info("Console Server Verticle Started Successfully. Listening to {} port",
TestService.serviceConfiguration.getPort());
}
I am able to receive cookies in browser and send it back along with updated X-XSRF-TOKEN attached to the header
Everything works fine in my local but when deploying in VM I get the below error for all post requests
ctx.fail(403, new IllegalArgumentException("Token signature does not match"));
from csrf handler of vertx.
Here are the frontend code to add x-xsrf-token when sending requests to backend
createXsrfHeader(headers: HttpHeaders) {
let xsrfToken = Cookies.get('XSRF-TOKEN')
let sessionToken = Cookies.get('vertx-web.session')
if(xsrfToken)
headers = headers.append('X-XSRF-TOKEN', xsrfToken);
// if(xsrfToken && sessionToken)
// headers = headers.append('Cookie', `XSRF-TOKEN=${xsrfToken}; vertx-web.session=${sessionToken}`);
return headers;
}
[Adding header to post request]
callPostRequest(subUrl: string,reqData: any) {
let headers = new HttpHeaders();
headers = this.createAuthorizationHeader(headers);
headers = this.createXsrfHeader(headers);
return this.http.post<any>(this.basicApiUrl+subUrl, reqData, {
headers: headers,
withCredentials : true
}).pipe(map(resData => {
// console.log(resData);
return resData;
}));
}
[Adding header to put request]
callPutRequest(subUrl: string,reqData: any) {
let headers = new HttpHeaders();
headers = this.createAuthorizationHeader(headers);
headers = this.createXsrfHeader(headers);
return this.http.put<any>(this.basicApiUrl+subUrl, reqData,{
headers: headers,
withCredentials : true
}).pipe(map(resData => {
// console.log(resData);
return resData;
}));
}
[Adding header to delete request]
callDeleteRequest(subUrl: string,reqData?: any) {
let headers = new HttpHeaders();
headers = this.createAuthorizationHeader(headers);
headers = this.createXsrfHeader(headers);
return this.http.delete<any>(this.basicApiUrl+subUrl, {
headers: headers,
withCredentials : true
}).pipe(map(resData => {
// console.log(resData);
return resData;
}));
}
Is there any ways to solve it.
I believe your problem is here:
router.route() // <--- HERE
.handler(
CSRFHandler.create(vertx, csrfSecret())
.setCookieHttpOnly(false))
.handler(sessionHandler);
You are telling the application to create a new CSRF token for each request that is happening, instead of being specific of which end points are really form-based endpoints.
Imagine the following, your form is on /student/form your browser may request:
/student/form (new CSRF token: OK)
/images/some-image-in-the-html.png (new CSRF token: probably Wrong)
/css/styles.css (new CSRF token: probably Wrong)
...
Now the issue is that the 1st call did correctly generated a token, but the following 2+ will generate new tokens too and these won't match the 1st so your tokens are always misaligned.
You probably need to be more specific with the resources you want to protect, from your code I am assuming that you probably want something like:
router.route(""/student/*") // <--- Froms are always here under
.handler(
CSRFHandler.create(vertx, csrfSecret())
.setCookieHttpOnly(false))
.handler(sessionHandler);
Be careful if calling other endpoints would affect the forms too. Note that you can add multiple handlers per route, so you can be more explicit with:
router.route(""/student/add")
// 1st always CSRF checks
.handler(
CSRFHandler.create(vertx, csrfSecret())
.setCookieHttpOnly(false))
// and now we the handler that will handle the form data
.handler(this::handleAddUser)

vertx Router no response

I wrote a dispatcher which routing a request to backend server, and response from backend is encrypted. When I decrypt the response body and write to RoutingContext response. Client can't receive response.
code like below
Router router;
router.routeWithRegex(patter).failureHandler(this::onFailure).handler(this::onRequest);
private void onRequest(Routing context){
...
HttpClient client = vertx.createHttpClient(new HttpClientOptions());
HttpClientRequest requestToBackend =
client.request(method, port, backendHost, uri, backendRsp -> onBackendResponse(context, backendRsp));
context.request().handler(body -> handleReq(requestToBackend));
context.request().endHandler((v) -> requestToBackend.end());
}
private void onBackendResponse(RoutingContext context, io.vertx.core.http.HttpClientResponse backendRsp) {
....
backendRsp.handler(data -> {
byte[] decrypt = decrypt(data);
context.request().response().write(data); // this works fine
// context.request().response().write(Buffer.buffer(decrypt)); // change to this, client can't receive response then
});
backendRsp.endHandler((v) -> context.request().response().end());
}
finally worked out, I changed the response body (shorter than origin), but not modify the header "content-length". so client keep waiting..

Servicestack Session is null only when using JWT

This fails on SessionAs in the baseservice in Postman when I authenticate via JWT. But when I use Basic Auth it works fine. Anyone know why?
Apphost
Plugins.Add(new AuthFeature(() => new CustomUserSession(),
new IAuthProvider[]
{
new BasicAuthProvider(), //Sign-in with HTTP Basic Auth
new JwtAuthProvider(AppSettings) {
AuthKeyBase64 = AppSettings.GetString("jwt.auth.key"),
RequireSecureConnection = false,
}, //JWT TOKENS
new CredentialsAuthProvider(AppSettings)
})
{
BaseService
public class ServiceBase: Service
{
public IUserAuth UserAuth
{
get
{
var session = SessionAs<AuthUserSession>();
return AuthRepository.GetUserAuth(session.UserAuthId);
}
}
}
Your SessionAs<T> needs to match the UserSession Type registered in the AuthFeature plugin which is CustomUserSession.
ServiceStack's JwtAuthProvider populates the UserAuthId in the JWT's sub JWT Payload so you should check the Raw HTTP Headers to make sure the JWT Token is being sent, either in HTTP's Authorization Header as a BearerToken or in the ss-tok Cookie. If it is being sent you decode the JWT sent in https://jwt.io to make sure it contains a valid payload, in this case it contains a "sub" property in the JWT payload containing the UserAuthId of the user being authenticated.

Unable to set values in the map using webclient call response

I am unable to get values filled in the map after making a web client call and using the response of the previous Mono.Here is the code I have tried.The value of parameters.size() comes out to zero.Not able to get the reason as to why the value is not filled.I basically want to return age ( and not Mono object)
from this method.Using block gives an error block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-3.
Map<String, String> parameters = new HashMap<String,String>();
Mono<Person> obj = webClient
.post()
.uri("dummy url")
.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
.retrieve()
.bodyToMono(Person.class)
.flatMap(resp -> {
parameters.put("name", resp.getName());
parameters.put("age", resp.getAge());
return Mono.just(new Person(resp.getName(),resp.getAge()));
}
);
System.out.println(parameters.size());
Please suggest where I am wrong and solution to fix the same.
Since this is about collecting and using a token of some sort collected from a previous HTTP call, your best bet is to delegate all that to an ExchangeFilterFunction.
An ExchangeFilterFunction is a filter that is executed on the client side for each outgoing request. Here is a very, very naïve implementation of such a filter:
class TokenFilterFunction implements ExchangeFilterFunction {
private final AtomicReference<String> token = new AtomicReference<>();
#Override
public Mono<ClientResponse> filter(ClientRequest req, ExchangeFunction next) {
if (this.token.get() == null) {
return fetchToken(next).then(sendRequest(req, next));
}
else {
return sendRequest(req, next);
}
}
private Mono<ClientResponse> sendRequest(ClientRequest req, ExchangeFunction next) {
ClientRequest request = ClientRequest.from(req)
.header("Token", this.token.get()).build();
return next.exchange(request);
}
private Mono<Void> fetchToken(ExchangeFunction next) {
ClientRequest tokenRequest = ClientRequest.create(HttpMethod.GET,
URI.create("https://example.com/token")).build();
return next.exchange(tokenRequest).doOnNext(res -> {
this.token.set(res.headers().header("Token").get(0));
}).then();
}
}
This could automatically call the token endpoint to fetch a token when needed and directly chain with the request you asked in the first place. Again, such an implementation should be much more complex than that, handling domains, errors, and more.
If you're using some authentication technology, such a filter might be implemented already in Spring Security in a much, much better way.
You can configure it on your client during the building phase, like:
WebClient webClient = WebClient.builder().filter(new TokenFilterFunction()).build();

How do I add a SOAP Header using Java JAX-WS

A typical SOAP client request using JAX-WS might be
FooService service = new FooService();
FooPort port = service.getFooPort();
FooPayload payload = new FooPayload();
payload.setHatSize(3);
payload.setAlias("The Hat");
...
port.processRequest(payload);
This generates an HTTP request content something like
<?xml ... ?>
<S:Envelope xmlns:S="http://...soap-envelope">
<S:Body>
<!-- payload -->
</S:Body>
</S:Envelope>
By manipulating the arguments to the port.processRequest() call you can only affect the "payload" part. You can't affect the outer part of the XML message.
I want to insert a SOAP header just before the SOAP Body
<S:Header>
<X:Security xmlns:X="http://...wsssecurity...>
<X:BinarySecurityToken>kjh...897=</X:BinarySecurityToken>
</X:Security>
</S:Header>
How do I do that?
Thanks Nuno,
Just as soon as I work out how to log in properly to stackoverflow.com I'll do the right thing with your reply.
In the mean time here's the code I ended up with:
FooService service = new FooService();
service.setHandlerResolver(new HandlerResolver() {
public List<Handler> getHandlerChain(PortInfo portInfo) {
List<Handler> handlerList = new ArrayList<Handler>();
handlerList.add(new RGBSOAPHandler());
return handlerList;
}
});
FooPort port = service.getFooPort();
FooPayload payload = new FooPayload();
payload.setHatSize(3);
payload.setAlias("The Hat");
...
port.processRequest(payload);
and
class RGBSOAPHandler implements SOAPHandler<SOAPMessageContext> {
public Set<QName> getHeaders() {
return new TreeSet();
}
public boolean handleMessage(SOAPMessageContext context) {
Boolean outboundProperty =
(Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outboundProperty.booleanValue()) {
SOAPMessage message = context.getMessage();
try {
SOAPEnvelope envelope = context.getMessage()
.getSOAPPart().getEnvelope();
SOAPFactory factory = SOAPFactory.newInstance();
String prefix = "X";
String uri = "http://...wsssecurity...";
SOAPElement securityElem =
factory.createElement("Security",prefix,uri);
SOAPElement tokenElem =
factory.createElement("BinarySecurityToken",prefix,uri);
tokenElem.addTextNode("kjh...897=");
securityElem.addChildElement(tokenElem);
SOAPHeader header = envelope.addHeader();
header.addChildElement(securityElem);
} catch (Exception e) {
System.out.println("Exception in handler: " + e);
}
} else {
// inbound
}
return true;
}
public boolean handleFault(SOAPMessageContext context) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void close(MessageContext context) {
//
}
}
you might want to look at handlers and handler chains.- I recently had to add a cookie to a given Webservice call and that was how i did it, just created a handler that intercepted the initial call and injected the cookie, you can also manipulate the call headers with a Pivot Handler
for add Soap header, if you implement the WS on the web application server, the Was will add security part at header , after you have configure as per WS-SECURITY standard , such as web-policy etc. I don't understand why need add yourself except the encrypted content part , such as encrypted password etc