Angular6 - SpringBoot Basic auth

28 views Asked by At

I have installed nvm 1.1.7 and Node.js version 8.11.1.

Now I have installed angular@cli version 6.1.3 and I create an Angular project with ng new.

I'm trying to do a Basic Authentication with SpringBoot as server. I have followed a tons of guides but I cannot set authentication params inside HttpHeader.

If I wrote:

var headers_object = new HttpHeaders();
headers_object.set('Content-Type', 'application/json');
headers_object.set('Authorization', 'Basic ' + btoa('guest:guest1234'));

And then:

console.log(headers_object.get('Content-Type'));

it prints null.. If I wrote:

const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'application/json'})
};
console.log(httpOptions.headers.get('Content-Type'));

It prints application/json. If I check the HttpHeaders code, I can see clearly the set method.

In my package.json I see:

"@angular/animations": "^6.1.0",
"@angular/common": "^6.1.0",
"@angular/compiler": "^6.1.0",
"@angular/core": "^6.1.0",
"@angular/forms": "^6.1.0",
"@angular/http": "^6.1.0",
"@angular/platform-browser": "^6.1.0",
"@angular/platform-browser-dynamic": "^6.1.0",
"@angular/router": "^6.1.0",
"core-js": "^2.5.4",
"rxjs": "6.0.0",
"zone.js": "~0.8.26"

Whats wrong??

-------------------------- UPDATE -----------------------

I manage to send the (I think..) headers param as follows:

let httpHeaders = new HttpHeaders()
          .set('Authorization', 'Basic ' + btoa('guest:guest1234'))
          .set('Content-Type', 'application/json'); 

console.log(httpHeaders.get('Content-Type')); // print correct
const httpOptions = {
  headers: httpHeaders
};
console.log(httpOptions.headers.get('Content-Type')); // print correct

return this.http.get('http://localhost:8080/hello', httpOptions); // return 401!!

I'm really going mad for this stupid thing... PS: Cors are disabled by Chrome extension.. and with Postman I reach the server...

1

There are 1 answers

0
CoderJammer On

Solved.. problem was server side.. I forget:

.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()

Inside Spring Security Configuration class. Anyway with Postman I could still reach the server even without the code above.. I still have doubts about it:

var headers_object = new HttpHeaders();
headers_object.set('Content-Type', 'application/json');
headers_object.set('Authorization', 'Basic ' + btoa('guest:guest1234'));
console.log(headers_object.get('Content-Type')); // printing null

I'm absolutely new to Angular and I will search a Typescript 2.9 documentation for it.

Any help (or documentation hint) is highly appreciate!