[Fixed] Unauthenticated error while fetching user data

Issue

i’am using Laravel as an endpoint and angular as a frontend to create an simple app this problem shows after i loggedin i tried to get the current authenticated
user data every time it shows this message "unauthenticated"

AuthController.php

class AuthController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login', 'signup' ]]);
    }  
     /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function userProfile() {
        $user = Auth::user();
        return $user;
    }
}

this is the service of http calls


import { HttpClient, HttpResponse ,HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { TokenService } from './token.service';



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

  constructor(private http:HttpClient,
    private Token:TokenService,
    
) { }
  userData(){
    return this.http.get('http://localhost:8000/api/profile');
  }
}

profile component

and this is how i make the requeset into the component

Solution

You are sending the request as anonymous
You must specify the authentication in your request

import { HttpClient, HttpResponse ,HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { TokenService } from './token.service';



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

  constructor(private http:HttpClient,
    private Token:TokenService,
    
) { }
  userData(){
    return this.http.get('http://localhost:8000/api/profile', {
        // Send the authentication token here 
        headers: {
            'Authorization': 'Bearer ' + userToken
        }
    });
  }
}

Leave a Reply

(*) Required, Your email will not be published