0

I'm trying to send an http GET request and receiving a JSON response containing a list of users. I've developed a simple authentication process and, everytime a user does the login, an authorization token is stored in the Local Storage. I need to send the GET request with the token in the header of the request.

The result is a 401 - Unauthorized. My guess is that the token is not beeing sent, because it's the same error I get when I try to send the request without the token.

I've tried many different ways that I've found over the Internet, but, nothing so far.

Here's the service I use to get the list of users

import { RequestOptions, Headers } from '@angular/http';
import { User } from './../interfaces/user';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable, Inject } from "@angular/core";
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class UserService{
token: string;

constructor (private http: HttpClient) { }
getUsers(): Observable<any>{
    this.token = localStorage.getItem("auth-token");

    const header = new HttpHeaders();
        header.set('Authorization', 'Bearer '+ this.token),
        header.set('Content-Type', 'application/json'),
        header.set("Access-Control-Allow-Origin", "*");
        header.set("Access-Control-Allow-Credentials", "true");
        header.set("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        header.set("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Authorization, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");

    return this.http
        .get("http://localhost:50681/api/User", { headers: header })
        .map(res => console.log(res));
    }
}

I've allowed the CORS and everything needed on the backend.

Here's the error

Am I missing something? Any help is apreciated

3
  • I can't see any flaw in your client code, just to mention that all the Access-Control headers there are meant to be sent from the server to the client, not the other way around like you do. If you can, post the server code as well Commented Mar 20, 2018 at 18:22
  • This link might help : https://stackoverflow.com/a/45286959/7458082 Commented Mar 20, 2018 at 18:23
  • @Cristian The access control headers are there because it doesnt work without them, even if I have the CORS allowed on the backend :( Commented Mar 21, 2018 at 8:57

0