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











up vote
0
down vote

favorite












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

use IlluminateHttpRequest;

use AppHttpControllersController;
use AppUser;

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?










share|improve this question
























  • Need to pass 'Authorization': 'Bearer ${token}' as a header, also
    – Ohgodwhy
    Nov 9 at 15:13















up vote
0
down vote

favorite












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

use IlluminateHttpRequest;

use AppHttpControllersController;
use AppUser;

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?










share|improve this question
























  • Need to pass 'Authorization': 'Bearer ${token}' as a header, also
    – Ohgodwhy
    Nov 9 at 15:13













up vote
0
down vote

favorite









up vote
0
down vote

favorite











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

use IlluminateHttpRequest;

use AppHttpControllersController;
use AppUser;

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?










share|improve this question















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

use IlluminateHttpRequest;

use AppHttpControllersController;
use AppUser;

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?







angular laravel rest http-headers jwt






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 9 at 16:48









georgeawg

32k104865




32k104865










asked Nov 9 at 15:03









Jay Marz

54231833




54231833












  • Need to pass 'Authorization': 'Bearer ${token}' as a header, also
    – Ohgodwhy
    Nov 9 at 15:13


















  • Need to pass 'Authorization': 'Bearer ${token}' as a header, also
    – Ohgodwhy
    Nov 9 at 15:13
















Need to pass 'Authorization': 'Bearer ${token}' as a header, also
– Ohgodwhy
Nov 9 at 15:13




Need to pass 'Authorization': 'Bearer ${token}' as a header, also
– Ohgodwhy
Nov 9 at 15:13












1 Answer
1






active

oldest

votes

















up vote
0
down vote













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





share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53228222%2fhow-to-properly-append-jwt-token-in-request-header-in-angular-7-laravel-5-7%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













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





    share|improve this answer

























      up vote
      0
      down vote













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





      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









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





        share|improve this answer












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






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 9 at 15:15









        Ali

        332213




        332213






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53228222%2fhow-to-properly-append-jwt-token-in-request-header-in-angular-7-laravel-5-7%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to pass form data using jquery Ajax to insert data in database?

            National Museum of Racing and Hall of Fame

            Guess what letter conforming each word