Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kenprogrammer's avatar

Angular and Laravel Sanctum Authentication

The code snippet below is an Angular service to authenticate a user using Laravel Sanctum:

auth-service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Router } from '@angular/router';

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

  private baseURL = "http://localhost:8000/api";

  constructor(private http: HttpClient,public router: Router) { }

  login(username: string, password: string): Observable<boolean> {
    return this.http.post<{token: string}>(this.baseURL+'/login', {email: username, password: password})
      .pipe(
        map(result => {
          localStorage.setItem('access_token', result.token);
          return true;
        })
      );
  }

  getToken() {
    return localStorage.getItem('access_token');
  }

  logout() {
    let removeToken = localStorage.removeItem('access_token');

    if (removeToken == null) {
      this.router.navigate(['login']);
    }
  }

  public get isLoggedIn(): boolean {
    //TODO: Check token expiry and other security checks
    return (localStorage.getItem('access_token') !== null);
  }
}

And the API response is as follows:

{
    "status": "success",
    "status_code": 200,
    "token": "19|fkZLjymuH9kjyviGodxNC1S3Fo0RkExHW7VABApU",
    "user": {
        "id": 1,
        "name": "John Doe",
        "email": "[email protected]",
        "email_verified_at": "2022-07-16T06:25:52.000000Z",
        "created_at": "2022-07-16T06:25:52.000000Z",
        "updated_at": "2022-07-16T06:25:52.000000Z"
    }
}

My first question is, is it secure to store token in local storage.? If not what's the best alternative? There's a general claim that tokens should not be stored in local storage but all SPA authentication tutorials teach this approach.

Secondly, if am using spatie permissions or Laravel Gates for authorization how can I store them on the frontend so that I can be able to show or hide menus based on what user is allowed to access?

0 likes
2 replies
giorgioLaraDev's avatar
  1. also in my opinion set the token in local storage is not safe at 100%. I love laravel and i'm building an api system to use with an angular frontend app. Before this idea i used firebase with angular but at the same time also firebase auth api respond with a token and in all video i've seen that the token went in the local storage

  2. i'm not sure how to use this in angular because i did this system with no problem for a web app with laravel (not for a api system), but i think that you can store a "role_user" in database and use it with the protecting route in angukar o api laravel

1 like

Please or to participate in this conversation.