Securing Angular Applications with Laravel Sanctum for Authentication

Posted by

Angular Authentication with Laravel Sanctum

Angular Authentication with Laravel Sanctum

Authentication is an important aspect of web development, especially when building APIs. Laravel Sanctum is a package that allows you to easily authenticate users in your Laravel application. In this article, we will explore how to use Angular to interact with a Laravel API that is secured with Sanctum.

Setting up Laravel Sanctum

First, you need to install Sanctum in your Laravel application. You can do this using Composer:

composer require laravel/sanctum

Next, publish the Sanctum configuration file:

php artisan vendor:publish --provider="LaravelSanctumSanctumServiceProvider"

Then, run the migrations to set up the necessary tables:

php artisan migrate

Finally, add the Sanctum middleware to your API routes in the api.php file:

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Setting up Angular

To interact with the Laravel API secured with Sanctum, we will use Angular. First, create a new Angular project:

ng new my-app

Next, install the Angular HTTP module:

npm install @angular/common @angular/http

Then, create a service in Angular to handle the authentication requests to the Laravel API. Here is an example service:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

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

  constructor(private http: HttpClient) { }

  login(credentials) {
    return this.http.post('http://your-api-url/login', credentials);
  }

  logout() {
    return this.http.post('http://your-api-url/logout', {});
  }

  getUser() {
    return this.http.get('http://your-api-url/user');
  }
}
    

Using the AuthService in Angular Components

Now that we have the AuthService set up, we can use it in Angular components to authenticate users. Here is an example of how to use the AuthService in an Angular component:

import { Component } from '@angular/core';
import { AuthService } from './auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {

  credentials = {
    email: '',
    password: ''
  };

  constructor(private authService: AuthService) { }

  login() {
    this.authService.login(this.credentials).subscribe((response) => {
      // Handle successful login
    });
  }

}
    

With this setup, you can now authenticate users in your Angular application using a Laravel API secured with Sanctum. Remember to handle error responses and add additional security measures as needed.