angular / angular-cli

CLI tool for Angular
https://cli.angular.dev
MIT License
26.78k stars 11.98k forks source link

Chrome is giving the Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'Authorization: Bearer ' is not a valid HTTP header field name #3253

Closed vdoolla closed 7 years ago

vdoolla commented 7 years ago

Please provide us with the following information:

OS?

Windows 7

Versions.

Please run ng --version. If there's nothing outputted, please run in a Terminal: node --version and paste the result here: angular-cli: 1.0.0-beta.20-4 node: 6.9.1 os: win32 x64

Repro steps.

Was this an app that wasn't created using the CLI? What change did you do on your code? etc. I have created the app with CLI capture

Environments – Angular2 with CLI + Boot Strap4 is Front End ( localhost:4200) Spring boot + Security +JWT + REST Ful Controllers for Back End (localhost:8080)

Chrome is giving the Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'Authorization: Bearer ' is not a valid HTTP header field name the same piece of code is working fine with IE.

I have been breaking my head from last two weeks and did lot of googling and unable to resolve the issue. As I am running out of time I am posting this question here hoping some Angular2 Gods will provide suggestions to resolve this issue.

Environments – Angular2 with CLI + Boot Strap4 is Front End ( localhost:4200) Spring boot + Security +JWT + REST Ful Controllers for Back End (localhost:8080)

Here is the scenario:

Login Screen

Onsubmit - Passing the Credentials to the Spring Boot Security to Authenticate.

onSubmit() {

 this.loginService.authenticateUser(this.loginUserDtls)
 .subscribe( 
  data => {
    let token=  JSON.parse(JSON.stringify(data))._body;
    console.log("TOKEN  VALUE "+token) ;
    this.loginService.sendToken(token).subscribe( 
    data => {
        let dataRet=  JSON.parse(JSON.stringify(data))._body;
        console.log("data received  "+dataRet);
     }
    )

 });

On Successful authentication Spring Security generating the JWT Token and sending the token back to fort end keeping it in the response header as below

response.addHeader("Authorization", "Bearer " + JWT);

Issue 1- Some reason Angular 2 (localhost:4200) response header is missing the Authorization header details which is placed in the Spring Boot Security Services (localhost:8080)

For Issue 1- I had a workaround by sending the JWT token in the response body.

After extracting the token the from response body, I am invoking a different restful service by passing token in the Angular 2 request Header as below :

sendToken(token) {

var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
headers.append('Authorization', 'Bearer '+ token);
headers.append('Accept', 'application/json');

return this.http.get('http://localhost:8082/users', {headers:headers});

}

The above worked is working fine in IE but when testing the same thing in Chrome getting the Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'Authorization: Bearer ' is not a valid HTTP header field name. Also please verify the screenshot for more detailed console log.

I had tried the above code with RequestOptions withCredentials = true also but no luck with Chrome.

Please kindly post your suggestions to resolve the issue.

The log given by the failure.

Normally this include a stack trace and some more information.

Mention any other details that might be useful.


Thanks! We'll be in touch soon.

clydin commented 7 years ago

The screenshot error shows an invalid field value not name. Header fields can only be ascii characters.

vdoolla commented 7 years ago

Hi Clydin, I have verified JWT Token it has only ASCII Characters.

Below is the key - eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsInNjb3BlcyI6IkFETUlOIiwiaXNzIjoiVEVTVCIsImlhdCI6MTQ3OTk0MjI5MCwiZXhwIjoxNDc5OTQyMzUwfQ.oBhh90hvqRBvOWQR5UY5dP-0V22o0fRjt0dhrDi3g7OBycN1qwnsmZvnjwQcqz0O_bLbo9mLLNn5fUmJ8ctwog capture

Attached is the screenshot with Key token. Please kindly let me know if you have any other suggestions.

manekinekko commented 7 years ago

this issue doesn't seem to be related to the CLI. Please post your question on stackoverflow as mentionned here: https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question thanks.

wulfsberg commented 7 years ago

Wild random guess: From the screenshot, it looks like you have a line break as part of your string after the base-64 encoding.

vdoolla commented 7 years ago

Hi, Thank you for your response. I am able to resolve this issue. This issue is due to CORS. Chrome is making a preflight and server is not setting header due to this during actual call chrome is not able to recognize Authorization header.

shrma21294 commented 7 years ago

@JavaCoder12 How did you resolve the issue ???

vdoolla commented 7 years ago

@Shrma21294 - As per my experience Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'Authorization: Bearer ' is not a valid HTTP header field name issue is not related to the Angular2/Front end code. If you are also facing similar issue my understanding is you are trying to call some backend services those are hosted at different server/port number. In order to resolve this issue place enable CORS at the service level to accept the call from Angular2/Frontend code and accept all the headers that are being passed from front end to service layer. In my scenario my backend is hosted on Springboot hence I have added filter to accept the preflight calls from Frontend app.

nbeuchat commented 6 years ago

'Authorization: Bearer ' should not be the header name. The header should be: 'Authorization' and the header value should be: 'Bearer [YOUR TOKEN HERE]'

To be honest, I had this issue in React and I somehow got here. I suppose this is the same issue. Hope this helps someone!

ghetal commented 6 years ago

Hello... I am facing the same issue. I am using .Net api. So, in webapi.config file I am specifying following line according to @JavaCoder12 solution. But still my issue is not solved.

config.EnableCors();

What is still missing?

vsergione commented 6 years ago

Hi, on my side the problem was that I was setting the header using something like this: setHeader("Authorisation:","Bearer [TOKEN_HERE]"). As one can notice, after the Authorisation follows a colon. Well, that was just wrong. So just make sure that the header name contains only the name and no other marks.

juanfurattini commented 6 years ago

in config/application.rb

module YourApp
  class Application < Rails::Application
    # Rails 5
    config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*', headers: :any, methods: [:get, :post, :options, :patch] # patch is the trick for headers
      end
    end
    # Rails 3/4
    config.middleware.insert_before 0, "Rack::Cors" do
      allow do
        origins '*'
        resource '*', headers: :any, methods: [:get, :post, :options]
      end
    end
  end
end
rootux commented 6 years ago

In my case I had a special \n char at the end of my header text which caused all the mess. Keeping it for future me

angular-automatic-lock-bot[bot] commented 5 years ago

This issue has been automatically locked due to inactivity. Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.