Retrofit 2.1 Internal Server Error with Post - django

I am using Retrofit 2.1 and when i am posting an object to my server, it gives me Internal server error with status code = 500, but i try to to post from my backend, it works like a charm, I am sure this is not server's problem.
Undoubtedly, i should use retrofit as a singleton:
//return api if not null
HereApi getApi(){
if (api == null) {
api = getRetrofit().create(HereApi.class);
}
return api;
}
//returns restadapter if not null
Retrofit getRetrofit(){
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl("my endpoint")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
and this method that i post Here object:
void createHere(Here here){
List<Here> list = new ArrayList<>();
list.add(here);
Call<List<Here>> call = getApi().createHere(list);
call.enqueue(new Callback<List<Here>>() {
#Override
public void onResponse(Call<List<Here>> call, Response<List<Here>> response) {
Log.i(TAG, "onResponse: "+response.message());
}
#Override
public void onFailure(Call<List<Here>> call, Throwable t) {
}
});
}
I tried to post a list with single object inside and to post one object alone, but still status code is 500 ;*(
This is my api service interface:
public interface HereApi{
#GET("/lessons/")
Call<List<Lesson>> getLesson(#QueryMap Map<String,String> map);
#Headers({
"Content-Type: application/json",
"Vary: Accept"
})
#POST("/heres/")
Call<List<Here>> createHere(#Body List<Here> list);
#GET("/heres/")
Call<List<Here>> getHeres(#QueryMap Map<String,String> map);
}
I have written backend in Django + Django-rest-framework:
When I try to post from this, it just works:
I need your help guys, i have only one day to complete this project!!!

Hi I think there is a datetime conversation issue.
Use Jackson formating attonation in order to properly serialize datetime field.

Related

AppSync Java authenticate with IAM

I am trying to update my appsync client to authenticate with IAM credentials. In case of API_KEY I set the API_KEY_HEADER like so: request.addHeader(API_KEY_HEADER, this.apiKey); Is there a similar way to authenticate in a Java client with IAM credentials? Is there a header I can pass in to pass in the secret and access keys like here: https://docs.amplify.aws/lib/graphqlapi/authz/q/platform/js#iam? Or should I just be using a cognito user pool as a way to authenticate the request?
According to AWS Documentation we need to use sign requests using the process documented here: https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html and steps listed here: https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html.
I also found an implementation here: https://medium.com/#tridibbolar/aws-lambda-as-an-appsync-client-fbb0c1ce927d. Using the code above:
private void signRequest(final Request<AmazonWebServiceRequest> request) {
final AWS4Signer signer = new AWS4Signer();
signer.setRegionName(this.region);
signer.setServiceName("appsync");
signer.sign(request, this.appsyncCredentials);
}
private Request<AmazonWebServiceRequest> getRequest(final String data) {
final Request<AmazonWebServiceRequest> request =
new DefaultRequest<AmazonWebServiceRequest>("appsync");
request.setHttpMethod(HttpMethodName.POST);
request.setEndpoint(URI.create(this.appSyncEndpoint));
final byte[] byteArray = data.getBytes(Charset.forName("UTF-8"));
request.setContent(new ByteArrayInputStream(byteArray));
request.addHeader(AUTH_TYPE_HEADER, AWS_IAM_AUTH_TYPE);
request.addHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_GRAPHQL);
request.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(byteArray.length));
signRequest(request);
return request;
}
private HttpResponseHandler<String> getResponseHandler() {
final HttpResponseHandler<String> responseHandler = new HttpResponseHandler<String>() {
#Override
public String handle(com.amazonaws.http.HttpResponse httpResponse) throws Exception {
final String result = IOUtils.toString(httpResponse.getContent());
if(httpResponse.getStatusCode() != HttpStatus.SC_OK) {
final String errorText = String.format(
"Error posting request. Response status code was %s and text was %s. ",
httpResponse.getStatusCode(),
httpResponse.getStatusText());
throw new RuntimeException(errorText);
} else {
final ObjectMapper objectMapper = new ObjectMapper();
//custom class to parse appsync response.
final AppsyncResponse response = objectMapper.readValue(result, AppsyncResponse.class);
if(CollectionUtils.isNotEmpty(response.getErrors())){
final String errorMessages = response
.getErrors()
.stream()
.map(Error::getMessage)
.collect(Collectors.joining("\n"));
final String errorText = String.format(
"Error posting appsync request. Errors were %s. ",
errorMessages);
throw new RuntimeException(errorText);
}
}
return result;
}
#Override
public boolean needsConnectionLeftOpen() {
return false;
}
};
return responseHandler;
}
private Response<String> makeGraphQlRequest(final Request<AmazonWebServiceRequest> request) {
return this.httpClient.requestExecutionBuilder()
.executionContext(new ExecutionContext())
.request(request)
.execute(getResponseHandler());
}

How to test the redirected routes with zuul routes filters in zuulProxy

I am following this link.
https://stackoverflow.com/a/57611351/7103694
What I am missing is this part on how to mock the filter i had used for my zuul Proxy.
This is my error log.
com.netflix.zuul.exception.ZuulException: Filter threw Exception
...
Caused by: .com.demo.example.exception.AccessTokenMissingException: No access token found in request headers.
I have a custom prefilter to check for Authorization header.
public class PreRouteFilter extends ZuulFilter {
#Override
public String filterType() {
return "pre";
}
#Override
public int filterOrder() {
return 1;
}
#Override
public boolean shouldFilter() {
return true;
}
#Override
public Object run() throws ZuulException {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
String header = request.getHeader("Authorization");
// Check header if it contain AUTHORIZATION key and value starting with "Bearer "
if (header == null || !header.startsWith("Bearer ")) {
ctx.set("error.status_code", HttpServletResponse.SC_UNAUTHORIZED);
throw new AccessTokenMissingException("No access token found in request headers.");
}
return null;
}
}
I added my filter via this configuration.
#Configuration
public class FilterConfig {
#Bean
public PreRouteFilter routeFilter() {
return new PreRouteFilter();
}
}
in your test, you need to create a request and in that add a header for Bearer token based Authorization.
something like this,
1. create a RequestContext, -
RequestContext context = new RequestContext();
create a MockHttpServletRequest and add the Auth header to it.
MockHttpServletRequest httpRequest = new MockHttpServletRequest();
httpRequest.setMethod("GET");
String authHeader = "Bearer " + "your sample token string";
httpRequest.addHeader("Authorization", authHeader);
httpRequest.setRequestURI("/<whateverURI>");
set the Http request in the context,
context.setRequest(httpRequest);
Set this context as the current test context,
RequestContext.testSetCurrentContext(context);
Now, you can run the filter,
yourFilter.run();

How to get a CompletableFuture from Jetty's HttpClient?

Is it possible to use issue an asynchronous HTTP request using Jetty and get back a CompletableFuture?
I read the docs but could not find any examples of doing so. I found internal usage of CompletableFuture but I couldn't figure out how to access it using the public API.
UPDATE: I need the CompletableFuture to return the response body as well (not just the response code and headers).
I have been using this with jetty client 9.4.x
var completable = new CompletableFuture<ContentResponse>();
client
.newRequest(uri)
.send(new CompletableFutureResponseListener(completable));
where
public class CompletableFutureResponseListener extends BufferingResponseListener {
private final CompletableFuture<ContentResponse> completable;
public CompletableFutureResponseListener(
CompletableFuture<ContentResponse> completable) {
this.completable = completable;
}
#Override
public void onComplete(Result result) {
if (result.isFailed()) {
completable.completeExceptionally(result.getFailure());
} else {
var response =
new HttpContentResponse(
result.getResponse(),
getContent(),
getMediaType(),
getEncoding());
completable.complete(response);
}
}
}
It's trivial to convert a CompleteListener into a CompletableFuture in this way:
CompletableFuture<Result> completable = new Promise.Completable<>();
httpClient.newRequest(...).send(result -> {
if (result.isFailed()) {
completable.completeExceptionally(result.getFailure());
} else {
completable.complete(result);
}
});
However, you are right that this may be done by HttpClient itself. Track this issue.

Angular2 ASP.NET Core AntiForgeryToken

I have an Angular2 app. It is running within ASP.NET 5 (Core).
It makes Http calls to the controller which is working fine.
But now I need to establish Cross Site Scripting projection.
How do I generate a new token on each Http request and then subsequently perform the AntiForgeryToken check in Angular2 apps?
Note: My data forms in Angular are not produced from an MVC view but entirely written in Angular2 and call web services only.
All the examples I have seen are out dated and do not work / do not work fully.
How do I integrate AntiForgeryToken checks in Angular2 against ASP.NET 5 where forms are pure Angular?
Thanks.
A custom action filter is not necessary. It can all be wired up in Startup.cs.
using Microsoft.AspNetCore.Antiforgery;
(...)
public void ConfigureServices(IServiceCollection services)
{
services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
(...)
}
public void Configure(IApplicationBuilder app, IAntiforgery antiforgery)
{
app.Use(next => context =>
{
if (context.Request.Path == "/")
{
//send the request token as a JavaScript-readable cookie, and Angular will use it by default
var tokens = antiforgery.GetAndStoreTokens(context);
context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions { HttpOnly = false });
}
return next(context);
});
(...)
}
Then all you need in your controllers is the [ValidateAntiForgeryToken] decorator wherever you want to enforce that a token is provided.
For reference, I found this solution here - AspNet AntiForgery Github Issue 29.
I am using a action filter to send the request tokens.
Simply apply it to the actions you want a new antiforgery token, e.g. Angular2 SPA, WebAPI action, etc.
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class AngularAntiForgeryTokenAttribute : ActionFilterAttribute
{
private const string CookieName = "XSRF-TOKEN";
private readonly IAntiforgery antiforgery;
public AngularAntiForgeryTokenAttribute(IAntiforgery antiforgery)
{
this.antiforgery = antiforgery;
}
public override void OnResultExecuting(ResultExecutingContext context)
{
base.OnResultExecuting(context);
if (!context.Cancel)
{
var tokens = antiforgery.GetAndStoreTokens(context.HttpContext);
context.HttpContext.Response.Cookies.Append(
CookieName,
tokens.RequestToken,
new CookieOptions { HttpOnly = false });
}
}
}
/* HomeController */
[ServiceFilter(typeof(AngularAntiForgeryTokenAttribute), IsReusable = true)]
public IActionResult Index()
{
return View();
}
/* AccountController */
[HttpPost()]
[AllowAnonymous]
[ValidateAntiForgeryToken]
// Send new antiforgery token
[ServiceFilter(typeof(AngularAntiForgeryTokenAttribute), IsReusable = true)]
public async Task<IActionResult> Register([FromBody] RegisterViewModel model)
{
//...
return Json(new { });
}
Register the attribute in Startup, and configure Antiforgery service to read the request token form "X-XSRF-TOKEN" header.
public class Startup
{
// ...
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddScoped<AngularAntiForgeryTokenAttribute>();
services.AddAntiforgery(options =>
{
options.HeaderName = "X-XSRF-TOKEN";
});
}
}
I think you need to make custom AntiForgeryValidationToken attribute that supports sending token via header instead of form values. Then add token to header of every request from your Angular2 app to your api. Example here How do you set global custom headers in Angular2?
To validate the token from a header you can use something like this:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class ValidateHeaderAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException(nameof(filterContext));
}
var httpContext = filterContext.HttpContext;
if (httpContext.Request.Headers["__RequestVerificationToken"] == null)
{
httpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
httpContext.Response.StatusDescription = "RequestVerificationToken missing.";
filterContext.Result = new JsonResult
{
Data = new { ErrorMessage = httpContext.Response.StatusDescription },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
return;
}
var cookie = httpContext.Request.Cookies[System.Web.Helpers.AntiForgeryConfig.CookieName];
System.Web.Helpers.AntiForgery.Validate(cookie != null ? cookie.Value : null, httpContext.Request.Headers["__RequestVerificationToken"]);
}
}
Then you just add [ValidateHeaderAntiForgeryToken] on the methods in your controller. Note though, this is from a MVC 5, ASP.NET 4.5.2 project, so you may have to alter it slightly to adjust to .NET Core. Also I modified this to return a JSON result if the token is missing, you can remove that part if you don't handle the error response and output it to the user.
Credits for the core part of this attribute goes to: https://nozzlegear.com/blog/send-and-validate-an-asp-net-antiforgerytoken-as-a-request-header
The hard part is how to generate the AntiForgeryToken without using #Html.AntiForgeryToken() in pure Angular 2 application (without access to .cshtml files). I'm looking for an answer to that as well.

How to get header value in UploadStringCompletedEventHandler method ASP.NET (Web API Service using HttpClient)

In My Windows Phone 8 App, I create WebClient object and initiate the with UploadStringAsync. and Create webClientLogin.UploadStringCompleted using UploadStringCompletedEventHandler.
WebClient webClientLogin = new WebClient();
webClientLogin.Headers["content-type"] = "application/json";
webClientLogin.UploadStringCompleted += new UploadStringCompletedEventHandler(webClientUploadStringCompleted);
webClientLogin.UploadStringAsync(new Uri(URL + "LogIn"), "POST", stockiestData);
Here stockiestData is Encoded Using Encoding.UTF8
I Get response as well.
private void webClientUploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
var logindetails = JsonConvert.DeserializeObject<LogResponse>(e.Result);
}
But I need to get the Header in this above method (webClientUploadStringCompleted).
I send the header like follows HttpContext.Current.Response.AppendHeader("Msg","Checked");
This response created in WebApi
How to get this?
Able to get header values using sender Object in the following method.
private void webClientUploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
}
We have to cast this object as WebClient.
Following method shows how to send in WebApi
[HttpPost]
[ActionName("LogIn")]
public dynamic LogIn(List<Student> Student, HttpRequestMessage request)
{
if (Student!= null)
{
HttpContext.Current.Response.AppendHeader("Msg", "Resived");
}
Following code shows you how to get header value from Windows phone 8
private void webClientUploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
WebClient web = (WebClient)sender;
WebHeaderCollection myWebHeaderCollection = (WebHeaderCollection)web.ResponseHeaders;
var v = web.ResponseHeaders["Msg"];
}