S4L4H
S4L4H

Reputation: 452

Unauthorized response with valid token

I get unauthorized as response on every request after login successfully

this is some of my code (let me know if you need to see anything else):

Data provider on ionic

this.storageProvider.getToken().then(results => {
                      this.httpOptions = {
                      headers: new HttpHeaders({
                          'Content-Type': 'application/json',
                          'Authorization': 'Bearer ' + results,
                          'Accept': 'application/json',
                        })
                      };
                  });

public getTodayReservations() {
  //all reservations (not todays only)
    let _url = this.url + '/guides/reservations/all';
    return this.http.get(_url, this.httpOptions);
}

an this the config of my laravel api routes:

Route::prefix('v1')
->group(function () {

    Route::post('login', 'Api\UsersController@login');

    Route::middleware('auth:api')
        ->prefix('guides')
        ->group(function () {

            Route::get('/show', 'Api\UsersController@show');

            Route::get('/reservations/today', 'Api\ReservationsController@today');
            Route::get('/reservations/all', 'Api\ReservationsController@allRes');

        });
});

Request Headers:

Accept: application/json
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI.....
Content-Type: application/json
Origin: http://localhost:8100
Referer: http://localhost:8100/

Upvotes: 1

Views: 379

Answers (2)

Sam
Sam

Reputation: 1139

As you can this.storageProvider.getToken() return a promise and not a token.

try something like this :

export class HttpService {

  private httpOptions;

  constructor(){
   this.storageProvider.getToken().then(results => {
        this.httpOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + results,
            'Accept': 'application/json',
          })
        };
    });   
  }

Upvotes: 1

Abhay Maurya
Abhay Maurya

Reputation: 12277

Check response of this.storageProvider.getToken(), usually it has access_token key which you are supposed to use in order to authroize your app so your code, not the full promise so your code will be like:

this.storageProvider.getToken().then(tokenObject => {
    private httpOptions = {
        headers: new HttpHeaders(
            {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + tokenObject.access_token,
                'Accept': 'application/json',
            }
        )
    }; 
});

Of course, in your case, it might be some other key, that is why you should have a look at this.storageProvider.getToken() first and only send the actual access token when sending Authorization header.

Upvotes: 0

Related Questions