Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs.

Overview

Logo Laravel Sanctum

Build Status Total Downloads Latest Stable Version License

Introduction

Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs.

Official Documentation

Documentation for Sanctum can be found on the Laravel website.

Contributing

Thank you for considering contributing to Sanctum! The contribution guide can be found in the Laravel documentation.

Code of Conduct

In order to ensure that the Laravel community is welcoming to all, please review and abide by the Code of Conduct.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

License

Laravel Sanctum is open-sourced software licensed under the MIT license.

Comments
  • CSRF token mismatch

    CSRF token mismatch

    Might have missed something, but getting CSRF token mismatch after running a request to the API (after running the airlock/csrf-cookie, which seems to be returning everything fine)?

    Added the monorepo here for help: https://github.com/adicle/test-app

    Just testing a really really simple SPA test with API but still having the issue.

    opened by adicle 52
  • Receiving unauthenticated after successful login and receiving cookies

    Receiving unauthenticated after successful login and receiving cookies

    • Airlock Version: 1.0.0
    • Laravel Version: 7.0.1
    • PHP Version: 7.3.11
    • Database Driver & Version: 10.3.15-MariaDB Homebrew

    Description:

    After successfully hitting the airlock/csrf-cookie endpoint and logging in I still receive unauthenticated when hitting my API in subsequent requests. I can see the cookies being sent in the request (XSRF-TOKEN and the session) but it still will not authenticate with the airlock middleware.

    Screenshot 2020-03-04 at 10 24 16

    SESSION_DOMAIN=.hub.test AIRLOCK_STATEFUL_DOMAINS=front.hub.test

    Cors config:

    <?php
    
    return [
    
        /*
        |--------------------------------------------------------------------------
        | Laravel CORS Options
        |--------------------------------------------------------------------------
        |
        | The allowed_methods and allowed_headers options are case-insensitive.
        |
        | You don't need to provide both allowed_origins and allowed_origins_patterns.
        | If one of the strings passed matches, it is considered a valid origin.
        |
        | If array('*') is provided to allowed_methods, allowed_origins or allowed_headers
        | all methods / origins / headers are allowed.
        |
        */
    
        /*
         * You can enable CORS for 1 or multiple paths.
         * Example: ['api/*']
         */
        'paths' => ['api/*', 'airlock/csrf-cookie', 'login', 'logout'],
    
        /*
        * Matches the request method. `[*]` allows all methods.
        */
        'allowed_methods' => ['*'],
    
        /*
         * Matches the request origin. `[*]` allows all origins.
         */
        'allowed_origins' => ['*'],
    
        /*
         * Matches the request origin with, similar to `Request::is()`
         */
        'allowed_origins_patterns' => [],
    
        /*
         * Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
         */
        'allowed_headers' => ['*'],
    
        /*
         * Sets the Access-Control-Expose-Headers response header.
         */
        'exposed_headers' => false,
    
        /*
         * Sets the Access-Control-Max-Age response header.
         */
        'max_age' => false,
    
        /*
         * Sets the Access-Control-Allow-Credentials header.
         */
        'supports_credentials' => true,
    ];
    

    Please can you give some guidance on this, I have tried all the relevant channels (slack, discord etc) and still not able to solve the issue

    Thank you

    opened by mattg1995 34
  • CSRF token mismatch and Unauthenticated

    CSRF token mismatch and Unauthenticated

    I can't get it to work with Nuxt in the front-end, firstly I got the **419 ** error number when I tried to access to /login which is a CSRF token issue, I disabled the **CSRF ** token by adding wildcard access in VerifyCsrfToken Middleware:

    protected $except = [
            '/*',
        ];
    

    I passed the login part with that, but I faced another one which is 401 ~ Unauthenticated: Although I'm in the stateful mode

    Laravel app is running on: http://localhost:8000/ Nuxt app is running on: http://localhost:3000/

    I think, there's an issue on ```EnsureFrontendRequestsAreStateful`` My Request using Axios as Nuxt Module:

    // I get the cookie [I'm using api as a prefix]
    this.$axios.$get('http://localhost:8000/api/csrf-cookie')
    // I pass the login
    .then(res => {
      this.$axios.$post('http://localhost:8000/login',
      {
        email: this.email,
        password: this.password
      }) 
      // I fail here with 401
      .then( data => {
        this.$axios.$get('http://localhost:8000/api/posts')
        .then( posts => console.log(posts))
      })
    })
    
    opened by mbougarne 31
  • Sanctum doesn't work with sub domains

    Sanctum doesn't work with sub domains

    • Sanctum Version: ^2.3
    • Laravel Version: ^7.0
    • PHP Version: 7.4
    • Database Driver & Version: MYSQL 5.7

    Description:

    Sub domains don't appear to work at all. I have followed the documentation to the T. From the documentation I should be able to use Laravel's auth scaffolding as per normal.

    Then when you do an axios call to the api routes using sanctum middleware, it should grab the session/cookie and do the authentication based on the auth scaffolding/ the user logging as per the standard login controller.

    Have I misunderstood the way the SPA part works? Apologies if I have.

    Steps To Reproduce:

    1. New laravel app with a sub domain on valet - composer install sanctum
    2. Add the SANCTUM_STATEFUL_DOMAIN in the env with the parent domain e.g video.mysite.test
    3. Add SESSION_DOMAIN to env .mysite.test
    4. Add axios.defaults.withCredentials = true; to bootstrap.js
    5. Add the additional kernel code based on the docs
    6. Add sanctum middleware to api.php : Route::group(['middleware' => 'auth:sanctum'], function () {
    7. Try and do a api call with axios, you will get 401 Unauthorized

    I have checked the documentation about 40 times and checked forums without any luck of getting a sub domain to work with api calls with Vue. Again apologies If I have misunderstood the way this works. If I have misunderstood, please point me in the right direction.

    opened by jamesh-purr 25
  • Local development cannot login

    Local development cannot login

    • Sanctum Version: 2.4.0
    • Laravel Version: 7.15.0
    • PHP Version: 7.4.6
    • Database Driver & Version: 10.1.44-MariaDB-0ubuntu0.18.04.1

    Description:

    On Sanctum 2.3 I do not have any problems, auth works greate with my Vue.js SPA. Once I update to 2.4 logging in with secure cookies works fine on deployed application, but local development is rendered useless since I cannot login.

    Steps To Reproduce:

    Update to 2.4 and use the following configuration: COOKIE_SAME_SITE_POLICY=strict SESSION_DOMAIN=localhost SANCTUM_STATEFUL_DOMAINS=localhost SESSION_DRIVER=cookie SESSION_LIFETIME=120 SESSION_SECURE_COOKIE=false

    needs more info 
    opened by averageflow 18
  • SPA Can not Log out

    SPA Can not Log out

    • Airlock Version: 1.0
    • Laravel Version: 7.0

    Description:

    After setting up following the setup here and configuring xsrf and cors, my SPA (in Angular) can log in but then cannot log out.

    The docs say that I should use the "standard, session based authentication services that Laravel provides" here so my login runs

    Auth::attempt([...]);
    

    and returns 200 or 401 on success or failure respectively.

    And as is written here within my logout function I call

    Auth::logout();
    

    but I receive

    Method Illuminate\Auth\RequestGuard::logout does not exist.
    

    The docs make no mention of modifying config/auth.php to set the api guard there, and so I haven't, it is still

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
        'hash' => false,
    ],
    

    The token that I can see through the authenticated user is a TransientToken and I cannot delete/revoke it..?

    So until the session expires a user is logged in and cannot be logged out.... Am I missing something?

    opened by cparkinsonMYCM 16
  • Sanctum: Issue with user logout case + TDD

    Sanctum: Issue with user logout case + TDD

    • Sanctum Version:^2.9
    • Laravel Version: ^8.12
    • PHP Version:7.3.9
    • Database Driver & Version: Mysql

    Description:

    I am writing a use case to logout a user, so on Logout request, I delete the user tokens so that token issued previously becomes invalid for further requests, but on the second request, the user is still logged in.

    I have searched online, many other instances of such issues exist with no solution https://laracasts.com/discuss/channels/testing/tdd-with-sanctum-issue-with-user-logout-case

    Steps To Reproduce:

    1. Create Laravel app with Sanctum.
    2. Create Two Endpoint : Login and Logout (Protect Logout with auth:sanctum)
    3. Create test Case: send a request to login.
    4. Send two request to logout route. observed behaviour: Both requests will succeed Expected Behavior: only the first request should succeed, the second request should fail.

    My code:

    //  route/api.php
    Route::post('/login',[AuthenticateController::class,"login"])->name("login");
    
    Route::post('/logout',[AuthenticateController::class,"destroy"])->middleware("auth:sanctum")->name("logout");
    
    // login method
      public function login(Request  $request): array
        {
            $request->validate([
                'email' => 'required|email',
                'password' => 'required',
    //        'device_name' => 'required',
            ]);
    
            /** @var User $user */
            $user = User::where('email', $request->email)->first();
    
            if (!$user || !Hash::check($request->password, $user->password)) {
                throw ValidationException::withMessages([
                    'email' => ['The provided credentials are incorrect.'],
                ]);
            }
    
            return ["token" => $user->createToken($request->email)->plainTextToken];
        }
    
    //logout
      public function destroy(Request $request)
        {
    
            // Revoke the token that was used to authenticate the current request...
            /** @var User $user */
            $user = $request->user();
            /** @var \Laravel\Sanctum\PersonalAccessToken $accessToken */
            $accessToken = $user->currentAccessToken();
      
            $accessToken->delete();
    
    
            return response( null,204);
    
        }
    
     public function test_logout()
        {
            /** @var User $user */
            $user = User::factory()->create();
    
            $response = $this->post(route("login"),
                ["email"=>$user->email,"password"=>"password"]
            );
    
            $response->assertStatus(200)->assertJson([
                'token' => true,
            ]);
    
            $token = $response->json("token");
            $this->withHeader("Authorization","Bearer $token");
    
            $testResponse = $this->post(route("logout"));
            $testResponse->assertNoContent();
    
         
          $testResponse = $this->post(route("logout"));
            $testResponse->assertNoContent();  //this is supposed to fail.
    
        }
    
    
    opened by Cintrust 15
  • "logoutOtherDevices" doesn't work with Laravel Sanctum

    • Sanctum Version: 2.3.1
    • Laravel Version: 7.11.0
    • PHP Version: 7.4.4
    • Database Driver & Version: MariaDB 10.4.12

    Description:

    logoutOtherDevices doesn't work when used in conjunction with Laravel Sanctum. I'm trying to use it to logout a specific user from all its sessions, yet sessions aren't invalidated.

    Steps To Reproduce:

    Auth::guard('web')->setUser(User::find(1))->logoutOtherDevices(Str::random(12));
    

    Login with an user, use tinker to run previous command, notice it produces no effect on currently active sessions.

    opened by IlCallo 14
  • [3.x] Add expires_at functionality to tokens.

    [3.x] Add expires_at functionality to tokens.

    Adds an expires_at timestamp to tokens. If the expires_at has passed, the token can no longer be used.

    This may allow users to set different expiration times for different tokens. So you can create a token used for a one-time import that expires in automatically in a week, and a token that generates daily reports that doesn't expire.

    This also lets developers enforce different expiration times for different tokens based on the type of user, or the privileges of the token.

    opened by bjhijmans 13
  • Route Prefix with Sanctum as Middleware disables Route::bind

    Route Prefix with Sanctum as Middleware disables Route::bind

    • Sanctum Version: 2.7.0
    • Laravel Version: 8.11.2
    • PHP Version: 7.4.10
    • Database Driver & Version: Non required for bug.

    Description:

    When having a rout with a prefix and auth:sanctum as a middleware the Route::bind will not be executed.

    Steps To Reproduce:

    Either clone my example Repo or follow the steps below.

    laravel new bug-example
    cd bug-example
    composer require laravel/sanctum
    php artisan make:provider BindProvider
    

    In the BindProvider:

    public function boot()
        {
            // dd();
            Route::bind('binding', function () {
                dd();
            });
        }
    

    In the web.php

    <?php
    
    use Illuminate\Support\Facades\Route;
    
    Route::prefix('/{binding}')->group(static function () {
        Route::get('/no-auth', function () {
            return view('welcome');
        });
    
        Route::middleware('auth:sanctum')->group(function () {
            Route::get('/auth', function () {
                return view('welcome');
            });
        });
    });
    
    

    Then run: php artisan serve

    Now we have two routes:

    http://127.0.0.1:8000/exapleBind/no-auth
    http://127.0.0.1:8000/exapleBind/auth
    

    Both should return a blank page. The no-auth route returns a blank page. The auth route return a Route [login] not defined.

    When uncommenting the dd(); in the BindingProvider at the start of the boot method both requests will be blank.

    needs more info 
    opened by BartzLeon 13
  • The

    The "web" guard should be a configuration

    The cookies are handled by the SessionGuard, and you can have many as you want. I think most cases will be like me where we have one Guard for a UserProvider and a second Guard for a different UserProvider (like table users and customers).

    Anyways, I think this value should not be hardcoded: https://github.com/laravel/airlock/blob/master/src/Guard.php#L46 https://github.com/laravel/airlock/blob/master/src/Guard.php#L77

    enhancement 
    opened by filhocodes 12
Releases(v3.0.1)
Owner
The Laravel Framework
The Laravel Framework
Rinvex Authy is a simple wrapper for @Authy TOTP API, the best rated Two-Factor Authentication service for consumers, simplest 2fa Rest API for developers and a strong authentication platform for the enterprise.

Rinvex Authy Rinvex Authy is a simple wrapper for Authy TOTP API, the best rated Two-Factor Authentication service for consumers, simplest 2fa Rest AP

Rinvex 34 Feb 14, 2022
It's a Laravel 8 authentication markdown that will help you to understand and grasp all the underlying functionality for Session and API Authentication

About Auth Starter It's a Laravel 8 authentication markdown that will help you to understand and grasp all the underlying functionality for Session an

Sami Alateya 10 Aug 3, 2022
Laravel auth-boilerplate using sanctum

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Jigar Bhaliya 3 Mar 2, 2022
phpCAS is an authentication library that allows PHP applications to easily authenticate users via a Central Authentication Service (CAS) server.

phpCAS is an authentication library that allows PHP applications to easily authenticate users via a Central Authentication Service (CAS) server.

Apereo Foundation 780 Dec 24, 2022
Laravel Auth is a Complete Build of Laravel 8 with Email Registration Verification, Social Authentication, User Roles and Permissions, User Profiles, and Admin restricted user management system.

Laravel Auth is a Complete Build of Laravel 8 with Email Registration Verification, Social Authentication, User Roles and Permissions, User Profiles, and Admin restricted user management system. Built on Bootstrap 4.

Jeremy Kenedy 2.8k Dec 31, 2022
Provides a unified interface to local and remote authentication systems.

Aura.Auth Provides authentication functionality and session tracking using various adapters; currently supported adapters are: Apache htpasswd files S

Aura for PHP 125 Sep 28, 2022
API stubs for developing a plugin that provides a 2FA authentication factor in JobRouter®.

Authentication Factor API JobRouter® is a scalable digitisation platform which links processes, data and documents. Starting with JobRouter® 5.2, a se

JobRouter 4 Nov 4, 2021
A framework agnostic authentication & authorization system.

Sentinel Sentinel is a PHP 7.3+ framework agnostic fully-featured authentication & authorization system. It also provides additional features such as

Cartalyst 1.4k Dec 30, 2022
KeyAuth is an open source authentication system with cloud-hosted subscriptions available aswell

KeyAuth is an open source authentication system with cloud-hosted subscriptions available aswell

null 158 Dec 23, 2022
Laravel Passport is an OAuth2 server and API authentication package that is simple and enjoyable to use

Introduction Laravel Passport is an OAuth2 server and API authentication package that is simple and enjoyable to use. Official Documentation Documenta

The Laravel Framework 3.1k Dec 31, 2022
A Simple method to create laravel authentication for an existing laravel project.

Laravel Simple Auth A Simple method to create laravel authentication for an existing laravel project. Indroduction Why I created this kind of package?

Dasun Tharanga 10 Dec 14, 2021
Open source social sign on PHP Library. HybridAuth goal is to act as an abstract api between your application and various social apis and identities providers such as Facebook, Twitter and Google.

Hybridauth 3.7.1 Hybridauth enables developers to easily build social applications and tools to engage websites visitors and customers on a social lev

hybridauth 3.3k Dec 23, 2022
Simple readonly LDAP authentication with Laravel 5.2

ldap-auth Very basic READ ONLY LDAP authentication driver for Laravel 5.2+ Look HERE for the package for Laravel 5.1. However, only the 5.2 Version wi

Stan 26 Jun 20, 2021
A simple two factor authentication for laravel applications

Laravel 2fa A simple two factor authentication for laravel applications. Installation Require via composer Update database Replace authentication trai

Rezkonline 1 Feb 9, 2022
This is a simple laravel authentication built with livewire jetstream.

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Emmanuel Dada 1 Feb 4, 2022
Simple PHP Google Authentication Template

php-google-auth A php google authentication page project View Demo · Report Problems About The Project This is a small and easy project that I made to

Antonio 4 Nov 21, 2021
LogRegPHP is a simple authentication module coded in object-oriented PHP.

LogRegPHP is a simple authentication module coded in object-oriented PHP. It provides you with some helper classes to help you get on speed with your project.

NIXX 1 Sep 27, 2022
Hej! is a simple authentication boilerplate for Socialite.

Hej! - a Socialite authentication flow implementation Hej! is a simple authentication flow implementation for Socialite. Out-of-the-box, Hej! can help

Renoki Co. 111 Oct 29, 2022
Simple user-authentication solution, embedded into a small framework.

HUGE Just a simple user authentication solution inside a super-simple framework skeleton that works out-of-the-box (and comes with an auto-installer),

Chris 2.1k Dec 6, 2022