I have a requirement where I have to send Dynamic query params on demand while sending it http request in mulesoft.
I am writing an expression to handle such scenario
something like this-
if(message.inboundProperties.'http.query.params'.param1 != null)
flowVars.params.put("param1", message.inboundProperties.'http.query.params'.param1);
if(message.inboundProperties.'http.query.params'.param2 != null)
flowVars.params.put("param2", message.inboundProperties.'http.query.params'.param2);
if(message.inboundProperties.'http.query.params'.param3 != null)
flowVars.params.put("param3", message.inboundProperties.'http.query.params'.param3);
//if it is a mandatory
flowVars.params.put("api_key", flowVars.apikey);
Creating hashmap but it failing in expression itself
can anyone help me on this
any leads would be appreciated.
You would need to set up an initial java.util.HashMap in a variable. Try something like this:
<set-variable variableName="params" value="#[new java.util.HashMap()]" mimeType="application/java" doc:name="Set params"/>
<expression-component doc:name="Expression"><![CDATA[if(message.inboundProperties.'http.query.params'.param1 != null)
flowVars.params.put("param1", message.inboundProperties.'http.query.params'.param1);
]]></expression-component>
<http:request config-ref="HTTP_Request_Configuration" path="/yourPath" method="{METHOD}" doc:name="HTTP {METHOD}">
<http:request-builder>
<http:query-params expression="#[flowVars.params]"/>
<http:header headerName="${header.correlationid}" value="#[sessionVars.correlationId]"/>
</http:request-builder>
</http:request>
Related
I am using Apigee API proxy and in the PreFlow part of the Proxy endpoint I have to make a http request. I created a JavaScript policy, where I tried using fetch to make the request, but when I call the endpoint, the response is ReferenceError: "fetch" is not defined. Does anybody have any suggestions what could work?
Apigee JavaScript Object Model exposes httpClient object.
More detail can be found in the docs .
I set a Variable to be called later and used the httpClient call like so:
//===================================
//== Set Function to pass response ==
//===================================
function onComplete (response, error){
//== Check if HTTP request was successful ==
//==========================================
if(response){
context.setVariable("responsePayload1", response.content);
}
//== Set Error Variable is it fails ==
//====================================
else {
context.setVariable("example.error", "Whoops: "+error)
}}
//==================================
//== Set Variable to run function ==
//==================================
var calloutResponse = httpClient.get("http://yourwebsitename.com/your-call-uri", onComplete);
By setting the variable it forces the JS to run the httpClient.get command in addition to running the above function.
I'm trying to authenticate the user after visiting the registration link
(link example: http://127.0.0.1:8000/confirm-email?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9F)
My code:
#app.get("/confirm-email", status_code=200, )
def confirm_email(
token: str = fastapi.Query(..., min_length=64, max_length=256,
db: Session = fastapi.Depends(database.get_db)):
if user := crud.read_user_by(db, column='current_token', value=token):
if user.created_datetime + timedelta(minutes=30) > datetime.now(): # TODO change minutes to days
return fastapi.responses.RedirectResponse(
url="http://127.0.0.1:8000/users/me",
headers={"access_token": token, "token_type": "bearer"})
else:
raise fastapi.HTTPException(
status_code=fastapi.status.HTTP_410_GONE,
detail="Confirmation link is expired")
else:
raise fastapi.HTTPException(
status_code=fastapi.status.HTTP_401_UNAUTHORIZED,
detail="Wrong token")
#app.get("/users/me")
def read_users_me(token: str = fastapi.Depends(oauth2_scheme),
db: Session = fastapi.Depends(database.get_db)):
try:
return services.get_user_by_token(db=db, token=token)
except Exception as e:
raise fastapi.HTTPException(
status_code=fastapi.status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
But every time I'm failing when trying to use /users/me endpoint (getting 401 error, UNAUTHORIZED).
Maybe I put the token in the wrong place or using wrong headers?
If using OAuth 2.0 and wanting to set the access_token in a request, tipically, it goes into the Authorization header like the example in the RFC: Authorization: Bearer mF_9.B5f-4.1JqM - in the example, mF_9.B5f-4.1JqM would be the value of the token.
It seems to me that you are accessing the users/me endpoint with the headers access_token: [token value] and token_type: "bearer". Instead, I believe the following header should be set: Authorization: Bearer [token value]
After a little researching, I figured out that redirection by specification can't have authorization headers (browser/client will just ignore it mainly). So even if headers are correct - it's nonsense. One possible solution to use URL.
I’m using network.request like this:
network.request( fullUrl, "POST", networkListener, params)
and receiving the response in my network listener as such:
local function networkListener( event )
if ( event.isError ) then
response = {};
else
response = json.decode(event.response);
end
end
I am receiving the body response of the request but I want to receive the request’s response headers as well. How can I achieve this?
Thanks a lot!
The documentation for network.request says:
network.request( url, method, listener [, params] )
listener (required)
Listener. The listener function invoked at various phases of the HTTP operation. This is passed a networkRequest event.
And the documentation for networkRequest links to event.responseHeaders, which gives this example:
-- Print the Content-Type header value for a response
local function networkListener( event )
print( "Content-Type of response is: " .. event.responseHeaders["Content-Type"] )
end
I use interceptor to check if a user is logged in every controller call like this :
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) {
if(request.getSession().getAttribute("user") == null) {
response.sendRedirect("redirect:/login?next="+
URLEncoder.encode(
request.getRequestURL().toString() + "" +
(request.getQueryString() != null ? "?" + request.getQueryString() : "")
,"utf-8");
return false;
}
return true;
}
It work fine for normal request but for ajax request i can't make a response.sendRedirect(..).
How to know if it's a ajax or normal request ?
How can i do it like if i got a ajax error ?
$.ajax({
.....
success : function(data) { ...... },
error : function(){
alert("login error"); // or
document.location = '/path/login' // or something else
}
});
There a other way to handle it rather than using interceptor ?
1. How to know if it's a ajax or normal request ?
You can check inside your interceptor for the existence of the X-Requested-With header. This header is always added to the ajax request by the jQuery library (to my knowing almost all major js libraries add it as well) with the purpose of preventing the Cross-Site request forgery. To figure out if the request is ajax, you can write your preHandle method like
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) {
String requestedWith = request.getHeader("X-Requested-With");
Boolean isAjax = requestedWith != null ? "XMLHttpRequest".equals(requestedWith) : false;
...
}
2. How can i do it like if i got a ajax error ?
As you've already noticed, ajax request don't recognize server side redirects, as the intention of the server side redirects is to be transparent to the client. In the case of an ajax request, don't do redirect rather set some status code to the response e.g. response.setStatus(respCode) or add a custom header e.g. response.setHeader("Location", "/path/login"), and read it through in the jQuery's complete method which is a callback that follows after either success or error, e.g.
$.ajax({
//...
complete: function(xhr, textStatus) {
console.log(xhr.status);
console.log(xhr.getResponseHeader('Location'));
// do something e.g. redirect
}
});
3. There a other way to handle it rather than using interceptor ?
Definitely. Checkout Spring Security. Its a framework, and adds a bit to the learning curve, but its well worth it. It will add much more than a custom solution, e.g. you'll get authorization mechanism on top of the authentication. When your application matures, you'll notice that the straigthforward implementation that you're on to now, has quite a few security flaws that are not hard to exploit e.g. session fixation, where spring security can easily protect you. There's plenty of examples online, and you'll get better support here on the SO in comparison to any custom solution. You can unit test it, an asset I personally value very much
You could simply:
Refuse ajax requests before the user is properly logged in
once the user logs in, set a security token in the session or somewhere
pass that token in the ajax request and use that token to validate on the server side prehandle
in your case you would check the existence of the token before running into the code
Also, the preHandle does not have to apply to every routes, you could also have different routes each with different authorisation, prehandle, code.
I am trying to use camel-restlet-2.14.0 to call an external REST service. The call to the rest service will depends on the query parameters passed by the user.i am trying to do this using the xml configuration.
<spring:camelContext trace="true">
<spring:route id="countries-fetch-route">
<spring:from uri="restlet:/verifyTest?restletMethod=GET">
</spring:from>
<spring:choice>
<spring:when>
<spring:simple>{header.abc} != null && {header.pqr} != null</spring:simple>
<spring:to uri="restlet:http://localhost:10080/TestRESTfulService/api/v1/av/verify/abc?abc={header.abc}&pqr={header.pqr}"></spring:to>
</spring:when>
</spring:choice>
<spring:transform>
<spring:simple>${body}</spring:simple>
</spring:transform>
</spring:route>
</spring:camelContext>
if anybody can help me to check the headers(query Params) that would be really helpful