Unauthorized response with valid token

我的未来我决定 提交于 2019-12-11 05:18:36

问题


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/

回答1:


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',
          })
        };
    });   
  }



回答2:


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.



来源:https://stackoverflow.com/questions/57074630/unauthorized-response-with-valid-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!