Unable to modify HttpHeader during HttpClient POST in Angular 5 - post

Using Angular 5 (http://localhost) and making HttpClient POST request to a REST service hosted on another server (http://192.168.200.75:5555).
Getting following error:-
Failed to load http://192.168.200.75:5555/rest/pub/ws/provider/requestToCSAF/: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
Service class looks like
import {Injectable} from '#angular/core';
import {HttpClient, HttpHeaders} from '#angular/common/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import {Observable} from 'rxjs/Observable';
import {RequestJSON} from './requestJSON';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Access-
Control-Allow-Origin': '*' })
};
#Injectable()
export class MyService {
private serviceUrl
= 'http://192.168.200.75:5555/rest/pub/ws/provider/requestToCSAF/';
constructor(private httpClient: HttpClient) {
}
postRequest(json: RequestJSON): Observable<RequestJSON> {
const _options = {headers: new HttpHeaders({'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'}) };
return this.httpClient.post(this.serviceUrl, json, httpOptions)
.catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
}
But request header looks as follow and throw No 'Access-Control-Allow-Origin' header is present on the requested resource error message:-
OPTIONS rest/pub/ws/provider/requestToCSAF/ HTTP/1.1
Host: 192.168.200.75:5555
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36
Access-Control-Request-Headers: access-control-allow-origin,content-type
Accept: */*
DNT: 1
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Referred: https://angular.io/tutorial/toh-pt6

On the REST service side, you should also add the header "Access-Control-Allow-Origin" with the value of the client server(http://localhost), so that the service will allow calls from the client.
you can find more details about cross-site requests here:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Server-Side_Access_Control

Related

Fetch with ReadableStream as Request Body

I'm trying to use fetch with a ReadableStream. In this example, the ReadableStream should simply repeat "Some data..." indefinitely.
fetch('/', {
method: 'POST',
body: new ReadableStream({
pull: function(controller) {
console.log('pull called!');
controller.enqueue('Some data...');
}
})
});
This doesn't work. While pull is executed once, no data is sent in the request body.
POST / HTTP/1.1
Host: example.com
Connection: keep-alive
Content-Length: 0
Origin: https://example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36
Accept: */*
Referer: https://example.com/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8
How can I make a ReadableStream (or any kind of stream where I can write dynamic data) usable with fetch?
Alternatively, if this isn't yet possible, could you please indicate this? Thank you.
Note: This is a more specific spin-off question from: Method for streaming data from browser to server via HTTP
We're working on making this work, see https://github.com/whatwg/fetch/pull/425 for the PR to the Fetch Standard. Once that is done you can expect this to make its way into browsers (slowly).

Principal is null when CSRF disabled

I'm creating a webapp that uses spring-boot-starter-security and spring-security-oauth2 to use Facebook for login.
To avoid implementing all that CSRF-stuff in angular 2 (and because it's just a toy project) I want to turn off CSRF.
I have implemented the following configuration:
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}
But now the Principal-Object is always null:
Task createTask(#RequestBody Task task, Principal principal) {
// do stuff
}
Why?
I guess I unintentionally overwrite the security config configured in my application.yaml, but even if I add an Order-Annotation it doesn't work :(
Edit:
Request headers (I created a Filter to add a XSRF-TOKEN cookie, ignore that):
POST /foo HTTP/1.1
Host: localhost:81
Connection: keep-alive
Content-Length: 15
Origin: http://localhost:81
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36
Content-Type: application/json
Accept: */*
Referer: http://localhost:81/create-task
Accept-Encoding: gzip, deflate
Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
Cookie: _ga=GA1.1.681162454.1458756836; JSESSIONID=F65FB28C14A8A2D870D18842DE855212; XSRF-TOKEN=551858ab-678e-4dcb-bc72-44fbc569ec41

DART HttpRequest does not provide authorization header for CORS OPTIONS request

I try to do a POST request with HttpRequest (dart:html) to call a rest service secured with basic authentication.
HttpRequest request = new HttpRequest(); // create a new XHR
var url = "http://localhost:8082/xyz";
request.open("POST", url, async: false); // POST the data to the server
String username = "foo";
String password = "bar";
final auth = CryptoUtils.bytesToBase64(UTF8.encode("$username:$password"));
request.setRequestHeader('authorization',"Basic $auth");
request.setRequestHeader('content-type',"application/json");
request.setRequestHeader("accept", "application/json");
String jsonData = '{"language":"dart"}'; // etc...
request.send(jsonData); //exception 401 Unauthorized
Before performing the POST call the OPTIONS call is performed (issued by dart:html) without the authorization header. This leads into an 401 Unauthorized response.
Request header:
Accept:*/*
Accept-Encoding:
gzip,deflate,sdch
Accept-Language:
en-US,en;q=0.8
Access-Control-Request-Headers:
authorization, content-type, accept
Access-Control-Request-Method:
POST
Cache-Control:
max-age=0
Connection:
keep-alive
Host:
localhost:8082
Origin:
http://localhost:63342
Referer:
http://localhost:63342/dart_client/test/all_test.html
User-Agent:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.0 (Dart) Safari/537.36
Reponse header:
Content-Length:
0
Date:
Mon, 02 Feb 2015 23:33:58 GMT
Server:
Jetty(9.2.7.v20150116)
WWW-Authenticate:
basic realm="xyzrealm"
Is there a way to provide the authorization header to the OPTIONS call?
Any suggestions would be great. Thanks
The OPTIONS request is made by the browser automatically and you can't modify that request. The server needs to allow the OPTIONS preflight request without authentication.
See http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0
The user credentials are excluded.

CORS in rails-api and angularJs

I've been trying out all kinds of solutions from the countless other questions on this topic, without any luck...
I'm trying to setup a rails-api project, with a front-end in AngularJs. They will be in different domains. I can make GET requests without any problem. But when I try to do a PUT, I get on Chrome console:
XMLHttpRequest cannot load http://0.0.0.0:3000/thingies/1.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:9000' is therefore not allowed access
Here's what my failed request looks like:
Remote Address:0.0.0.0:3000
Request URL:http://0.0.0.0:3000/thingies/1
Request Method:OPTIONS
Status Code:404 Not Found
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,ja;q=0.6,ko;q=0.4,pt;q=0.2,ro;q=0.2,zh-CN;q=0.2
Access-Control-Request-Headers:accept, content-type
Access-Control-Request-Method:PUT
Cache-Control:no-cache
Connection:keep-alive
Host:0.0.0.0:3000
Origin:http://localhost:9000
Pragma:no-cache
Referer:http://localhost:9000/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36
Response Headersview source
Connection:Keep-Alive
Content-Length:17164
Content-Type:text/html; charset=utf-8
Date:Tue, 26 Aug 2014 06:48:06 GMT
Server:WEBrick/1.3.1 (Ruby/2.1.1/2014-02-24)
X-Request-Id:xxxxxx-xxxxxxx-xxxxxx-xxxxxxxxxx
X-Runtime:0.027031
Here's my app.js in AngularJs:
angular
.module('myApp', [
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'restangular',
])
.config(function ($routeProvider,RestangularProvider, $httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common["X-Requested-With"];
$httpProvider.defaults.headers.common["Accept"] = "application/json";
$httpProvider.defaults.headers.common["Content-Type"] = "application/json";
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'HomeCtrl'
.otherwise({
redirectTo: '/'
});
RestangularProvider.setBaseUrl('http://0.0.0.0:3000');
});
This is in my Rails project:
application.rb:
class Application < Rails::Application
config.action_dispatch.default_headers.merge!({
'Access-Control-Allow-Origin' => '*',
'Access-Control-Request-Method' => '*'
})
end
My routes.rb, application_controller.rb and thingy_controller are the default scaffolded files. (I've tried modifying them according to other solutions for CORS, without any luck.)
I've used POSTMAN (Chrome Extension) as well, to see if I could use PUT. The requests went through without problems.
I'd really appreciate if someone could point me in the right direction with this!
Try add { 'Content-Type': 'application/x-www-form-urlencoded' } in your $http request like that
$http({
method : 'POST',
url : 'backend.json',
data : $.param($scope.yourFormData), // pass in data as string, important!
headers: { 'Content-Type': 'application/x-www-form-urlencoded' } // set the appropriate headers
})
The Problem is that CORS is blocking your requests. You have to provide the Service and the Application on the same host with the same port. To avoid this problem you could use a Proxy to "map" the url of the service to the url of your application.
Cheers
Nighthawk

Does HttpServer handle the same request twice?

Trying to set up a simple Dart HttpServer:
import 'dart:io';
void main() {
HttpServer.bind(InternetAddress.ANY_IP_V4, 80).then((server) {
server.listen((HttpRequest request) {
request.response.write('Hello, world.');
request.response.close();
print(new DateTime.now());
print(request.connectionInfo.remoteAddress);
print(request.method);
print(request.headers.toString());
print("--------------");
});
});
print("listing....");
}
When hitting localhost from a browser (Chrome), it appears as if the incoming request is handled twice:
listing....
2013-11-07 15:19:24.478
InternetAddress('127.0.0.1', IP_V4)
GET
host: localhost:80
connection: keep-alive
cache-control: max-age=0
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
user-agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
accept-encoding: gzip,deflate,sdch
accept-language: en-US,en;q=0.8
--------------
2013-11-07 15:19:24.554
InternetAddress('127.0.0.1', IP_V4)
GET
host: localhost:80
connection: keep-alive
accept: */*
user-agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
accept-encoding: gzip,deflate,sdch
accept-language: en-US,en;q=0.8
--------------
Those two requests look almost identical, except for the accept header. Doesn't look like the browser is firing up the request twice:
So, why does the request get handled twice?
EDIT: Dart SDK version 0.8.10.6_r30036
You don't output what is requested (the url member of the request instance) and that is the difference between the two requests.
The first request requests the file you try to open, probably /. The second request is issued internally by the browser and requests favicon.ico to display the icon in the address bar / tab title.

Resources