使用有效令牌的未经授权的响应

Unauthorized response with valid token

我在成功登录后对每个请求的响应都未授权

这是我的一些代码(如果您需要查看其他任何内容,请告诉我):

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

这是我的 laravel api 路由的配置:

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

        });
});

请求Headers:

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

尽你所能 this.storageProvider.getToken() return 一个承诺,而不是一个令牌。

尝试这样的事情:

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

检查 this.storageProvider.getToken() 的响应,通常它有 access_token 密钥,你应该使用它来授权你的应用程序,所以你的代码,而不是完整的承诺,所以你的代码将是这样的:

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

当然,在您的情况下,它可能是其他密钥,这就是为什么您应该先查看 this.storageProvider.getToken() 并且仅在发送 Authorization 时才发送实际访问令牌 header.