如何在Angular 7 + Laravel 5.7中的请求标头中正确附加JWT令牌

时间:2018-11-09 15:03:21

标签: angular laravel rest http-headers jwt

我在Angular 7应用中的UsersService中拥有此功能。

import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions, URLSearchParams } from '@angular/http';
import { ApiService } from '../../services/api.service';

@Injectable({
  providedIn: 'root'
})
export class UsersService {

  public headers: Headers;
  public options: RequestOptions;

  constructor(
    private http: Http,
    public api: ApiService
  ) {

    this.headers = new Headers({
      'Content-Type':'application/x-www-form-urlencoded',
      'X-Token': localStorage.getItem('token')
    });
    this.options = new RequestOptions({ headers: this.headers });

  }

  getAll(){

    return this.http.get(`${this.api.url}/api/users`, this.options);

  }

}

此服务会将HTTP请求发送到带有端点/users的Laravel 5.7应用

Laravel路线api.php

<?php

Route::group([

    'middleware' => 'api'
    // 'prefix' => 'auth'

], function ($router) {

    /**
     * Authentication API
     */
    Route::post('login', 'AuthController@login');
    Route::post('signup', 'AuthController@signup');
    Route::post('logout', 'AuthController@logout');
    Route::post('refresh', 'AuthController@refresh');
    Route::post('me', 'AuthController@me');

    /**
     * Users API
     */
    Route::get('users', 'UsersController@index');

});

Laravel UsersController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use App\User;

class UsersController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth:api');
    }

    /**
     * Get all Users
     * 
     */
    public function index()
    {

        $user = User::all();

        return response()->json($user);

    }
}

尝试呼叫所述端点时,它会返回错误:

message:"Unauthenticated."

如何正确附加JWT令牌以在端点中发送?

1 个答案:

答案 0 :(得分:0)

首先从

导入 HttpHeaders
import { HttpClient, HttpHeaders,HttpResponse } from '@angular/common/http';

private token=localStorage.getItem('token');

现在通过以下方式创建http标题

private httpOptions = {
    headers: new HttpHeaders({'Authorization': 'Bearer ' +this.token ,'Content-Type':'application/json', 'X-Requested-With':'XMLHttpRequest'})
  };