Insomnia gives longer String than retrofit - retrofit

I am making a request to my back-end server
insomnia gives right string : dT8d0XzxSaSNqErV4dPs5i: APA91bFOIAgXsu_YRw91PYZw1JdtBDZfeR8HZRn6jYa3f-ewaFYZ77weK8kEjrKexPkg0FFBfCSJCJDJSJGZZZGZZGZZZGZZGZZDGZZZGZZDGZZZGZZDGWG1
But retrofit somehow cuts the token off and gives me only 44 character string with that request
dT8d0XzxSaSNqErV4dPs5i: APA91bFOIAgXsu_YRw91
What might be wrong?
The data must return the same keys.
I am ensured that my endpoints are the same.
#Override
public void onResponse(Call<String> call, Response<String> response) {
EventBus.getDefault().post(new EventTu(response));
}

Related

Json data type response of IP rate limit API

I am using middleware provided by AspNetCoreRateLimit to rate limit incoming requests to an ASP.NET Core 2.x REST API web application.
Currently this library returns html responses for rejected requests. How can I make it return json responses instead?
You could custom your response in the IpRateLimitMiddleware.
IpRateLimitMiddleware
public class MyIpRateLimitMiddleware : IpRateLimitMiddleware
{
public MyIpRateLimitMiddleware(RequestDelegate next
, IOptions<IpRateLimitOptions> options
, IRateLimitCounterStore counterStore
, IIpPolicyStore policyStore
, IRateLimitConfiguration config
, ILogger<IpRateLimitMiddleware> logger)
: base(next, options, counterStore, policyStore, config, logger)
{
}
public override Task ReturnQuotaExceededResponse(HttpContext httpContext, RateLimitRule rule, string retryAfter)
{
//return base.ReturnQuotaExceededResponse(httpContext, rule, retryAfter);
var message = new { rule.Limit, rule.Period, retryAfter };
httpContext.Response.Headers["Retry-After"] = retryAfter;
httpContext.Response.StatusCode = 200;
httpContext.Response.ContentType = "application/json";
return httpContext.Response.WriteAsync(JsonConvert.SerializeObject(message));
}
}
Configure the middlware in Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//app.UseIpRateLimiting();
app.UseMiddleware<MyIpRateLimitMiddleware>();
//your rest middlware
}
Read the docs
If the request gets blocked then the client receives a text response like this:
Status Code: 429
Retry-After: 58
Content: API calls quota exceeded! maximum admitted 2 per 1m.
You can customize the response by changing these options HttpStatusCode and QuotaExceededMessage, if you want to implement your own response you can override the IpRateLimitMiddleware.ReturnQuotaExceededResponse. The Retry-After header value is expressed in seconds. (emphasis mine)

Zuul reverse proxy preserve URL

I have a microservce architecture with several services build using JHipster.
Inside one service i have implemented a zuul route filter.
public class TestZuulFilter extends ZuulFilter {
#Override
public String filterType() {
return "route";
}
#Override
public int filterOrder() {
return 5;
}
#Override
public boolean shouldFilter() {
String requestUri = RequestContext.getCurrentContext().getRequest().getRequestURI();
return "/serviceid/reverseproxy".equals(requestUri);
}
#Override
public Object run() {
// get url from id
String id = ctx.getRequest().getParameter("id");
Strign url = URLService.getURLFromId(id);
try
{
RequestContext ctx = RequestContext.getCurrentContext();
// redirect
ctx.setRouteHost(new URL(url));
} catch(MalformedURLException ex) {}
return null;
}
}
When a client call my service http://myservice/serviceid/reverseproxy?id=2 zuul redirects (http 302 status) the user to the url with id 2, in this case google.com.
How can i preserve the original request URL from the client ?
The url must remain http://myservice/serviceid/reverseproxy?url=2 instead of http://www.google.com
Thanks in advance.
It seems you misunderstood the concepts of redirection and proxification.
HTTP redirection means URL change because all the work is done by the client who ends up by making 2 request calls (one to your proxy and one to external service).
Here what you want is to proxify the original request to an external service (in your example google), it means that your filter should be a client of your external service. This way your original client makes only on request call and has no idea that it is talking to your external service.

DotNetOpenAuth.WebServerClient.XSRF-Session changes during callback

I'm trying to setup a simple Oauth2 login authentication. However I'm stuck at the callback that throws the following exception:
[ProtocolException: Unexpected OAuth authorization response received with callback and client state that does not match an expected value.]
DotNetOpenAuth.Messaging.ErrorUtilities.VerifyProtocol(Boolean condition, String unformattedMessage, Object[] args) +426
DotNetOpenAuth.OAuth2.WebServerClient.ProcessUserAuthorization(HttpRequestBase request) +771
The exact same problem is discussed over here
In my case the SessionID remains the same, but the DotNetOpenAuth.WebServerClient.XSRF-Session cookie changes it's value at the callback.
Implementation:
public void Authorize(HttpRequest request)
{
string callbackString = request.Url.AbsoluteUri;
Uri callbackUri = new Uri(callbackString);;
IAuthorizationState authorization = nimbleClient.ProcessUserAuthorization();
if (authorization == null)
{
// Kick off authorization request
nimbleClient.RequestUserAuthorization(returnTo: callbackUri);
}
else
{
//Get AccesToken
Uri.EscapeDataString(authorization.AccessToken);
}
Have you declared your cookie as constant, like below:
private const string XsrfCookieName = "DotNetOpenAuth.WebServerClient.XSRF-Session"
This would help to maintain the value even at callback.

Executing Code on Every Request

I need to run a validation routine looking for some header information on every request to the server. I would use OnActionExecuting in ASP.NET MVC, or an ActionInvoker, to run on every request, but I've been looking in Web API, and haven't found something specific.
If something could be implemented for both synchronous and asynchronous, that would be the best.
For Web API you should resort to MessageHandlers
Message handlers always run first, before anything else in the pipeline, and they are also able to run last (after Web API returns response, just prior to the response reaching the client).
More about message handlers can be found here - http://www.asp.net/web-api/overview/working-with-http/http-message-handlers.
And here is a simple example, validating an API key:
public class WebApiKeyHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
string apikey = HttpUtility.ParseQueryString(request.RequestUri.Query).Get("apikey");
if (apikey != "something")
{
HttpResponseMessage response = request.CreateErrorResponse(HttpStatusCode.Forbidden, "You can't use the API without the key.");
throw new HttpResponseException(response);
}
else
{
return base.SendAsync(request, cancellationToken);
}
}
}
In this example only request with the key "something": i.e./api/values/?apikey=something will be allowed, all other will be rejected.
In your case, you can simply access the request.Headers and validate whatever you need.

spring-mvc with resteasy character encoding problem on jetty server

I am trying to implement restful protocol on jetty server. I have runnable server and i can access it from my rest client. My server side project is a maven project. I have a problem about the character encoding.When i check response, before send it from controller, there is no encoding problem. But after i return response to client, i see broken data. Response header is UTF-8. Also i have a listener for this problem and i am setting to request and response to UTF-8. I guess problem happens when i try to write my response data to response.
#GET
#Path("/")
#Produces({"application/xml;charset=UTF-8","application/json;charset=UTF-8"})
public String getPersons(#Context HttpServletRequest request, #Context HttpServletResponse response) {
List<Person> persons = personService.getPersons(testUserId, collectionOption, null);
if (persons == null) {
persons = new ArrayList<Person>();
}
String result = JsonUtil.listToJson(persons);
//result doesnt has any encoding problem at this line
response.setContentType("application/json");
response.setContentLength(result.length());
response.setCharacterEncoding("utf-8");
//i guess problem happen after this line
return result;
}
Is there any jetty configuration or resteasy configuration for it? Or is there any way to solve this problem? Thanks for your helps.
Which resteasy version are you using? There is a known issue (RESTEASY-467) with Strings in 2.0.1 an prior.
These are your options:
1) force the encoding returning byte[]
public byte[] getPersons
and then
return result.getBytes("UTF8");
2) return List (or create a PersonListing if you need it)
public List<Person> getPersons
and let resteasy handle the json transformation.
3) return a StreamingOutput
NOTE: with this option the "Content-Length" header will be unknown.
return new StreamingOutput()
{
public void write(OutputStream outputStream) throws IOException, WebApplicationException
{
PrintStream writer = new PrintStream(outputStream, true, "UTF-8");
writer.println(result);
}
};
4) upgrade to 2.2-beta-1 or newer version.

Resources