Apigee remove URL string before forwarding request to target - apigee

I want to transform a URL before it is redirected to the target, removing a string. I have the following flow in Apigee:
USER -> APIGEE -> APPLICATION -> APIGEE -> USER
The user requests and then its URL should be rewritten removing bar from the URL.
BEFORE apigee.url.com/foo/bar/pBxATaojIn8tk5dvQdNJ
AFTER target.url.com/foo/pBxATaojIn8tk5dvQdNJ
I use Proxy Endpoints and Target Endpoints and try to rewrite using a PreFlow hook with Javascript in the Target Endpoint, without success rewriting the proxy.pathsuffix. How can I solve this?

I now use the following solution:
// Disable copy path
context.setVariable("target.copy.pathsuffix", false);
// Replace string in incoming proxy URL path
var proxyPathSuffix = context.getVariable("proxy.pathsuffix");
var fooBarAfter = proxyPathSuffix.replace('/fooToReplace', '');
// Fetch target outgoing url path
var targetBasePath = context.getVariable("target.basepath");
var urlPath = targetBasePath.concat(fooBarAfter);
// Replace outgoing url
var targetUrl = context.getVariable("target.url");
targetUrl = targetUrl.replace(targetBasePath, urlPath);
context.setVariable("target.url", targetUrl);
I came up with it looking at the available variables here. As this is JS, if someone comes up with a better solution I would be happy!

From my understanding proxy.pathsuffix is a read only variable so you can't override it.
Assign your target endpoint to target.url instead. (I usually use in Assign Message Policy of the request)
Example:
<AssignVariable>
<Name>target.url</Name>
<Ref>yourTargetUrlValue</Ref>
</AssignVariable>
In my Assign Message Policy of the request, I have added the block of code above for defined my target url.
You can assign directly like <Ref>http://test.com</Ref> or assign via variable like <Ref>{targetUrlVal}</Ref>
If you got the url from somewhere, don't forget to assign value to your variable before use it by using context.setVariable("targetUrlVal", "http://test-01.com");
Hopefully my answer will help you.

I solved this similar to how you did it. See my answer on another SO question that answers this.

Related

A good name for a URL path and query string and fragment?

URLs can be broken up into these components:
Sample URL: http://www.server.com:8080/path?query=string#fragment
protocol = http
host = www.server.com
port = 8080
path = /path
query = ?query=string
fragment = #fragment
Is there an established name for everything that comes after port (path, query, and fragment)? I was tempted to just call this "path" but that is not a good name as it does not include the query and fragment.
The IETF URI Spec defines the combination of these elements (path, query, and fragment) as a Relative Reference.
Perhaps "relative URL", as in "relative to Site Root"
The URL structure you are giving is containing the basic elements, and the fragment is usually coming before the query, the query in general is used when you are listing a part of data, so you need to access to it by this query, and parameters if needed.
Here a good review to list the steps for creating a good url.
there is no established name for everything together due to them all being different. Also you forgot the parameters part of the url. The parameters go in the query.

Define parameters as param request instad of endpoint url in fasthttprouter

I am using golangĀ“s fasthttprouter and have followed the examples and defined a router like this:
router.GET("/customer/account/detail/:accountId", myHandler.customerAccountDetailHandler)
Then I call to my service as http://locahost:9296/customer/account/detail/2
But I realised that I do not want to have the parameters as part of the endpoint , I rather prefer to use normal parameters by calling my service like this:
http://locahost:9296/customer/account/detail?accountId=2&sort=1
Is it possible to be done with fasthttprouter? How?
Thanks in advance
J
The query parameter should be accessible from the request context.
You should have a handler that takes a *fasthttp.RequestCtx argument. This RequestCtx can access the URI and the query params on that URI. That should look something like this:
ctx.URI().QueryArgs().Peek("accountId")
You'll have to update your handler to use this query parameter instead of the route param you were previously using. The same would also apply for the sort param.
Also, your router would have to be updated to route /customer/account/detail to your updated handler (i.e. you'll want to remove /:accountId from your route).
Your questions is similar to this one:
Get a request parameter key-value in fasthttp
You can retrieve the parameters of the request in this way:
token = string(ctx.FormValue("token"))
Have a look at my complete response here
https://stackoverflow.com/a/57740178/9361998
Documentation: https://godoc.org/github.com/valyala/fasthttp#RequestCtx.FormValue

UserManager.GenerateEmailConfirmationToken returning tokens unsuitable for URL transmission

I have a ASP.NET MVC 5 website, and I'm implementing an email confirmation process based on the template from Microsoft.
While I'm composing the email body text, first I construct the URL a user will use to "click to verify your address".
To generate the security token I call:
UserManager.GenerateEmailConfirmationTokenAsync(user.Id)
This produces a code such as:
pporPNj6KzdZ3BYG8vQsKJu3dPJMwGgh+ZEGhCNnf9X6F0AS0f6qCowOQwQNfpYkl14bgEsmyPTKya5H6N4n2na2n5PgO+wpoihXxQTA7G8pK/lUYskX3jy2iA/ZM8m4Vm0prTyUuhMgfDlV+wkbR336FBRIAbKJDwOWvHHbJBDQ21gW93hyzca0li66aI1H
Obviously, this wouldn't be valid in a URL, but even URL encoding won't solve IIS's hate of such a URL.
HTTP Error 404.11 - Not Found
The request filtering module is configured to deny a request that contains a double escape sequence.
In my UserManager implementation, I'm using the tutorial boilerplate code for a TokenProvider.
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider<SiteUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
How can I make these generated tokens a bit more URL friendly? What did potentially change that would prevent the ASP.NET's tutorial code not work?
It turns out that this token will get mangled by the built in class "UrlHelper" in a MVC controller, or Url in a WebAPI controller IF the target route lists these variables as part of the path, rather than the GET vars of the URL.
Eg: this call, creates a relative URL for the site route called "ConfirmEmail" and fills in the blanks
Url.Route("ConfirmEmail", new { userId = user.Id, code = code });
Before my route was:
[Route("register-email/{code}/{userId}", Name = "ConfirmEmail")]
Changing this to:
[Route("register-email", Name = "ConfirmEmail")]
Generates valid URLS that IIS can chew through. When these are not specified, they get appended after a ? mark as normal GET vars. No idea why IIS is picky like that, but there's the solution.

Using Fiddler: Inject cookie into all subsequent requests from initial request

I have a batch of requests in Fiddler, the first is a login request and returns a valid cookie. The rest need to use this cookie, I know I can break and edit headers but is it possible to automatically script this behaviour? I'm pretty new to Fiddler but it looks powerful so I'm hoping this is possible, anyone know how or where to start?
To manually add a header, use the Filters tab and use the Request Headers section.
To automatically add a header, click Rules > Customize Rules. Scroll to OnBeforeResponse and write code that stores the target cookie in a global variable declared just inside the Handlers function, e.g.
static var m_MyCookie: String;
Then, inside the OnBeforeRequest function, use that variable, e.g.
if (!String.IsNullOrEmpty(m_MyCookie)) oSession.oRequest["Cookie"] = (m_MyCookie + ";" + oSession.oRequest["Cookie"] )
If you're only trying to add this header to specific requests, use, for instance, the oSession.uriContains function to determine whether the target URL is one that you want to have the cookie.

How to get # value in query string from a URL coming from an API, not the current request

I get a returned url from using facebook api:
http://www.example.com/#access_token=BAAGgUj7asdasdasdasda4z3cBAFD5ZAyTOMIxtBpjIHsNwLfZC6L9gZAIdSIt3bKP96rg7yAlplMBDA9ZCndAKS9a7m4oRmRmJAxSdCueefweWJrlq3vQv3XaGqTOLofEMjJIVNCYZD&expires_in=0
But i am not sure how to get the token value? As its not in query string or Request.url
Any help?
You can't, assuming this is passed in on the current request, as anything after the # is never sent to the server.
You can capture it in JavaScript and use AJAX to send it to the server, but this will be on a different request.
If you mean you have this URL not from the current request, you can use the Uri class to parse a full URL and get the fragment:
var fragment = new Uri(theUri).Fragment;
var token = fragment.Split(new [] {'&','='}, StringSplitOptions.None)[1];
You can use HttpUtility.ParseQueryString to parse the URL then you can get the value by name e.g.
NameValueCollection query = HttpUtility.ParseQueryString(querystring);
string token = query["token"];
Check this Retrieving Anchor Link In URL for ASP.Net
you cannot get it from the server side, you will need to take if from client side first then pass it to the server in a hidden field or something similar
You have to look for "%23", because "#" is url-encoded to "%23"
reference:
http://www.w3schools.com/tags/ref_urlencode.asp
But you have to know also, that anchors are not available on server side!

Resources