Getting 401 error due wrong placement of token jwt error

Viewed 31
public getOrderID(filters: any) {
        let params = {
            orderID: filters.orderID,
        };
        let token = this._currentUser.getValue().token;
        const Headers = new HttpHeaders({
            'Content-Type': 'application/json',
            'Authorization': token
        }) || null;
        let response = this.apiService.get(`/user/order`, params, Headers);
        // let response = this.http.get(`https://fishry-storefront-apis-stg.azurewebsites.net/user/order?orderID=${params.orderID}`, { headers });
        return response
            .map(this.apiService.returnResponse)
            .catch(this.apiService.catchError);
    }

This is the code that I have been trying to use. It should return a response containing an ID but instead it is providing me 401 error. I have tried the commented way too. Please if anyone could tell me what am I doing wrong while sending the token.

let response = this.apiService.get(`/user/order`, params, Headers);
// let response = this.http.get(`https://fishry-storefront-apis-stg.azurewebsites.net/user/order?orderID=${params.orderID}`, { headers });

Expecting an ID

1 Answers

Per https://www.rfc-editor.org/rfc/rfc6750 the Authorization field should look like:

Authorization: Bearer <token_here>

So in your case it would be

const Headers = new HttpHeaders({
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token
        }) || null;

Edit: Something that can make your life easier is to also take a look at this article (https://medium.com/@ryanchenkie_40935/angular-authentication-using-the-http-client-and-http-interceptors-2f9d1540eb8). Big picture is that it is creating a custom HttpInterceptor which will automatically add the Bearer token to the request as it is being sent. This way you don't have to manually add it in the Headers.

Related