0

I've got a Django Rest Framework backend and a Angular frontend.
I use JWT for authentication. When I try to get a token I get the following result as JSON:

{
    "refresh": "jfksdajfkjsdkafjasdjfkjsdkfjksdfjfj8j2qfj2jjf",
    "access": "asjdfijajf8wjfw8ijf89wfj08jfw890ijf8wsf098wsfjaw"
}

My code looks like this:
Auth Service

private token: Observable<string>;

private params = {
    params: new HttpParams()
      .set('username', 'MYUSERNAME')
      .set('password', 'MYPASSWORD')
      .set('content-type', 'application/json')
  };

constructor(private http: HttpClient) { }

getToken(): Observable<any>{
    this.token = this.http.post('https://www.mywebsite.com/api-token', this.params);
    return this.token;
  }

Application


private url = 'https://www.mywebsite.com/api/movies';

private data = {
    headers: new HttpHeaders({
      'Authorization': `Bearer ${this.authService.getToken()}`,
      'content-type': 'application/json'
    })
  };

constructor(private http: HttpClient, private authService: AuthServiceService) { }

fetchMovies(): Observable<Movie[]> {
  console.log(this.data);
  return this.http.get<Movie[]>(this.url, this.data);
}

When I try to run this code i get a "bad_authorization_header"
Detail: "Authorization header must contain two space-delimited values"

I think the error occours because I pass the refresh and the access token together.
How can I extract the access token only?

Thanks for any help!

Janik Spies
  • 399
  • 7
  • 15
  • 2
    You need to subscribe it. But you may also have async problem if you set bearer like that in application. I suggest you to set to session while login and set to session there. – mr. pc_coder Jun 21 '20 at 18:28

1 Answers1

1

Change getToken To :-

getToken(): Observable<any>{
    return this.http.post('https://www.mywebsite.com/api-token', this.params).pipe(map((res)=>res.access));
  }

change data like :-

this.authService.getToken().subscribe((token)=>{
   this.data = = {
    headers: new HttpHeaders({
      'Authorization': `Bearer ${token}`,
      'content-type': 'application/json'
    })
});
Aakash Garg
  • 10,649
  • 2
  • 7
  • 25