I am trying to implement basic authorization in Angular 4 using the recently released HttpClient .
I am trying to connect to a Spring application running on Tomcat with open REST APIs.
I have the following code in my LoginComponent :
onSubmit(user){ console.log(user); const body = JSON.stringify({username: user.userName, password: user.password}); let headers = new HttpHeaders(); headers.append("Authorization", "Basic " + btoa("username:password")); headers.append("Content-Type", "application/x-www-form-urlencoded"); this.http.post('my url here',body, {headers: headers}).subscribe(response => { console.log(response); }, err => { console.log("User authentication failed!"); }); }
However, the request does not add the Authorization header at all.
This is the Chrome tools Network tab:

What am I doing wrong? How can I do this job?
Update 1: its still not working:
I changed two lines as below:
headers = headers.append("Authorization", "Basic " + btoa("username:password")); headers = headers.append("Content-Type", "application/x-www-form-urlencoded");
I get the header in the request, as expected. This is from Chrome :

However, the mail call still does not work.
On the server side, my code is:
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String authCredentials = request.getHeader("Authorization"); if(authCredentials == null) { logger.info("Request with no basic auth credentials {}", request.getRequestURL()); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; }
The bell never reaches do my stuff . authCredentials null .
This is from Chrome :

How to act?
Update 2: its work:
I needed to do both:
1) I had to change the headers line to what I did in Update 1, since HttpHeaders is immutable.
headers = headers.append("Authorization", "Basic " + btoa("username:password")); headers = headers.append("Content-Type", "application/x-www-form-urlencoded");
2) Now, based on your requirement, you have two options:
a) Use a proxy server as described here to solve the CORS problem without changing the end of your server.
b) Update the end of the server as described here and in some of the answers below to change the spring configuration.