DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • API and Security: From IT to Cyber
  • When APIs Go Wrong: Neglecting Rate Limiting
  • Secure Your API With JWT: Kong OpenID Connect
  • API Security: Best Practices and Patterns To Securing APIs

Trending

  • Introduction to Retrieval Augmented Generation (RAG)
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Agentic AI Systems: Smarter Automation With LangChain and LangGraph
  1. DZone
  2. Data Engineering
  3. Databases
  4. Laravel Sanctum SPA API Authentication: Part 1

Laravel Sanctum SPA API Authentication: Part 1

Learn how to set up Laravel Sanctum authenticate single page applications (SPAs) that need to communicate with a Laravel powered API.

By 
Razet Jain user avatar
Razet Jain
·
Jan. 12, 21 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
13.8K Views

Join the DZone community and get the full member experience.

Join For Free

Laravel Sanctum is a lightweight package to help make authentication in single-page or native mobile applications as easy as possible. Where before you had to choose between using the web middleware with sessions or an external package like Tymon's jwt-auth, you can now use Sanctum to accomplish both stateful and token-based authentication.

Installing Laravel Sanctum

First, let's actually install the package using Composer:

Shell
x
 
1
composer require laravel/sanctum

Then, we'll have to publish the migration files (and run the migration) with the following commands:

Shell
 




xxxxxxxxxx
1


 
1
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
2
php artisan migrate


The last part of Sanctum's installation requires us modifying the app\Http\Kernel.php file to include a middleware that will inject Laravel's session cookie into our app's frontend. This is what will ultimately enable us to pass and retrieve data as an authenticated user:

PHP
 




xxxxxxxxxx
1


 
1
'api' => [
2
    EnsureFrontendRequestsAreStateful::class,
3
    'throttle:60,1'
4
]


CORS & Cookies

You should ensure that your application's CORS configuration is returning the Access-Control-Allow-Credentials header with a value of True by setting the supports_credentials option within your application's cors configuration file to true.

In addition, you should enable the withCredentials option on your global axios instance. Typically, this should be performed in your resources/js/bootstrap.js file:

JavaScript
xxxxxxxxxx
1
 
1
axios.defaults.withCredentials = true;

 Authenticating

To authenticate your SPA, your SPA's login page should first make a request to the /sanctum/csrf-cookie route to initialize CSRF protection for the application:

JavaScript
 




xxxxxxxxxx
1


 
1
axios.get('/sanctum/csrf-cookie').then(response => {
2
    // Login...
3
});


During this request Laravel will set an XSRF-TOKEN cookie containing the current CSRF token. This token should then be passed in an X-XSRF-TOKEN header on subsequent requests, which libraries like Axios and the Angular HttpClient will do automatically for you.

Protecting Routes

To protect routes so that all incoming requests must be authenticated, you should attach the sanctum authentication guard to your API routes within your routes/api.php file. 

PHP
 




xxxxxxxxxx
1


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


API Laravel authentication

Published at DZone with permission of Razet Jain. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • API and Security: From IT to Cyber
  • When APIs Go Wrong: Neglecting Rate Limiting
  • Secure Your API With JWT: Kong OpenID Connect
  • API Security: Best Practices and Patterns To Securing APIs

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!