未经授权的回应以及有效的凭证

时间:2019-07-17 11:18:25

标签: laravel rest api ionic-framework ionic3

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

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

离子数据提供者

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

        });
});

请求标头:

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

2 个答案:

答案 0 :(得分:0)

您可以this.storageProvider.getToken()返回承诺而不是令牌。

尝试这样的事情:

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

答案 1 :(得分:0)

检查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标头时发送实际访问令牌的原因。