简体   繁体   中英

How to properly append JWT token in request header in Angular 7 + Laravel 5.7

I have this in my UsersService in my Angular 7 app.

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

  }

}

This service will send HTTP request to my Laravel 5.7 app with endpoint /users

Laravel Routes 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);

    }
}

When trying call the said endpoint it returns an error:

message:"Unauthenticated."

How to properly append the JWT Token to send in the endpoint?

First import HttpHeaders from

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

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

Now create http headeer in the following way

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM