GithubHelp home page GithubHelp logo

laravel / sanctum Goto Github PK

View Code? Open in Web Editor NEW
2.7K 49.0 282.0 356 KB

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

Home Page: https://laravel.com/docs/sanctum

License: MIT License

PHP 100.00%
laravel sanctum auth

sanctum's Introduction

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.

sanctum's People

Contributors

aalyusuf avatar alexjose avatar amaelftah avatar ankurk91 avatar bencomeau avatar canvural avatar cosmastech avatar crynobone avatar davidhsianturi avatar dellow avatar dewbud avatar doekenorg avatar driesvints avatar dshoreman avatar eliurkis avatar faustbrian avatar faytekin avatar filippofortino avatar jubeki avatar lukadriel7 avatar marzvrover avatar nunomaduro avatar phpclub avatar rahuldey12 avatar rennokki avatar richardkeep avatar rjchauhan avatar stevenbdf avatar taylorotwell avatar themsaid avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sanctum's Issues

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.

Front-end requests on unknown third-party domains

I have a backend API running on a subdomain api.example.com but then I have multiple front-ends, all which call the same API but are under different domains, some of which are not first party.

Is it possible to have some way of having third party applications request to use stateful authentication?

I was thinking of maybe having some form of callback which returns the valid urls here. I would be able to then return which referers are stateful and which ones arent dynamically.

I guess I could just extend the middleware and overwrite the fromFrontend method, hmmm

It would also be a great idea to add some form of helper method to determine if the request is coming from any of the stateful referrers, as my current /auth/login returns the auth token, and since I'm not using it in my front-ends I don't see any point in returning it.

Airlock Middleware causing Carbon date issues.

  • Airlock Version: 0.2.0
  • Laravel Version: 6.13
  • PHP Version: 7.2.24
  • Database Driver & Version: sqlsrv
  • OS: MacOS 10.14.6
  • Docker: Version: 2.2.0.0 Container: microsoft/mssql-server-linux 14.0.3048.4

Description:

Getting Data Missing error when accessing routes through auth:airlock
Issues are relating to: Carbon/Traits/Creator.php

Usual fix for Models with this issue is to add getDateFormat and fromDateTime functions to the model.

Steps to reproduce

Installed Airlock 0.20 on Laravel 6.13, using a docker container to run MSSQL.
Set up Airlock Middleware and Authentication Guard as per documentation.
Run the migration files, and set up a User using Tinker.
Accessing an Api route '/enquiry, EnquiryController@index' from an Axios call in VueJS.
EnquiryController@index has dd('test') which doesn't get executed.

If the Api route '/enquiry, EnquiryController@index' is outside of 'auth:airlock'. I get the correct dd response.

please implement SSO

Hello!
Good Job!
Im requesting SSO implemetation.
It is possible?

Case: SSO Auth server, makes User authenticated at multiple servers.

Thanks!

Single Action Controllers ( __invoke() ) constructor not authenticating session

  • Airlock Version: v0.2.1
  • Laravel Version: v6.17.0
  • PHP Version: 7.1
  • Database Driver & Version:

Description:

Not sure if I missed something, if it's by design or a bug.

Steps To Reproduce:

class TestController extends ApiController
{
    public function __construct(Request $request)
    {
        dd($request->user()); // null;
    }

    public function __invoke(Request $request)
    {
        dd($request->user()); // App\User;
    }
}

How do i get the signed in user in the constructor?

Adding additional data to createToken

Idea: adding a 3rd parameter to createToken() for custom columns

If your token has additional scope or tenant information.. being able to pass it in like:

createToken('token-name', ['*'], ['tenant_id' => 1'])

With an array merge.. would be convenient

$token = $this->tokens()->create(array_merge([
    'name' => $name,
    'token' => hash('sha256', $plainTextToken = Str::random(80)),
    'abilities' => $abilities,
], $values);

Otherwise, an observer works or $token->update($values) on the returned token

Feature Request: Add details how it works

I'm in the process of switching to a SPA (which is new to us).
We are evaluating whether we use airlock.

Can the repository or documentation explain exactly how it works and what security measures it takes.

Thanks.

Airlock::actingAs

I would really like to use this as an alternative to Passport for an API I am building, but a lot of my tests use Passport::actingAs for roles and permissions tests.

How could one go about mocking this functionality for the time being so I could write in tests like this:

   /**
     * Test DELETE /api/properties/{id}.
     *
     * @return void
     */
    public function testDeleteProperty()
    {
        Airlock::actingAs(
            factory(\App\User::class)->create()->attachRole('admin')
        );

        $property = factory(\App\Property::class)->create();
        $response = $this->deleteJson('/api/properties/' . $property->id);

        $response
            ->assertOk()
            ->assertJsonPath('message', 'Deleted property.');

        $this->assertSoftDeleted('properties', [
            'id' => $property->id,
        ]);
    }

It seems Airlock::useUserModel doesn't work

I faced an issue since I have the User Model in different namespace:

namespace App\Models;
ErrorException class_parents(): Class App\User does not exist and could not be loaded

The only way that help to solve it was updating the config\auth

'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],
],

When I tried to customize the User Model with Airlock::useUserModel() It doesn't work with me:

use Laravel\Airlock\Airlock;
use App\Models\User;
# I tried with different Model: use App\Models\Customer;
public function boot()
{
        Airlock::useUserModel(User::class);
}

Finally, it might be good to control the Airlock User Model from its config file

'users' => [
        'model' => App\Models\User::class,
],

Airlock with Cookie Token HttpOnly

In most cases for SPAs, it's not recommended to store token in localStorage for sending token to API server with Bearer authorization header for security issues.

Would you consider to add extra check for cookie token in airlock/Guard.php to check if headers contains valid token in cookie which is set as HttpOnly.

The response sent from controller's login method could be this:

return response()
   ->json(['success' => 'User logged.'], 200)
   ->withCookie(cookie(config('airlock.cookie_token_name'), $token, $minutes)); 

Next request to API server would automatically include the token to access protected routes with auth:airlock middleware.

Sorry, if it's totally not relevant at all here and have misunderstood the idea behind airlock.

Exception during Installation

Got this when running composer require

   Symfony\Component\Debug\Exception\FatalThrowableError  : Call to undefined method App\Http\Kernel::prependToMiddlewarePriority()

  at /site/vendor/laravel/airlock/src/AirlockServiceProvider.php:107
    103|     protected function configureMiddleware()
    104|     {
    105|         $kernel = $this->app->make(Kernel::class);
    106| 
  > 107|         $kernel->prependToMiddlewarePriority(EnsureFrontendRequestsAreStateful::class);
    108|         // $kernel->prependMiddlewareToGroup('api', EnsureFrontendRequestsAreStateful::class);
    109|     }
    110| }
    111|

  Exception trace:

  1   Laravel\Airlock\AirlockServiceProvider::configureMiddleware()
      /site/vendor/laravel/airlock/src/AirlockServiceProvider.php:54

  2   Laravel\Airlock\AirlockServiceProvider::boot()
      /site/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:32

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?

1 guard for all?

  • Airlock Version: 0.1.0
  • Laravel Version: 6.13.1
  • PHP Version: 7.3.9
  • Database Driver & Version: MySQL

Description:

When using airlock as a guard, it assumes that guard on non-auth required routes. The issue with this is that when wanting to fallback on passport, it's impossible.

The issue I present is that I'm using passport for my bearer tokens and airlock for my session authentication. Airlock sits at the front, and if it fails to find what it needs, I'd like it to then check the passport guard.

Possible solution: fallback to desired guard if session is not found.

Test user not removed / multiple test "request" calls

  • Airlock Version: 0.1.0
  • Laravel Version: 6.12.0
  • PHP Version: 7.3
  • Database Driver & Version: MySQL

Description:

Making multiple json calls in a single test doesn't check the token from the withHeaders()

So the following calls still have the previous user in the request even with revoked tokens.

Steps To Reproduce:

If you make multiple requests in a test to prove a previously removed token no longer works:

$user = factory(User::class)->create();

$token = $user->createToken('default')->plainTextToken;

$this->withHeaders(['Authorization' => "Bearer {$token}"])
    ->json('GET', 'api/auth/logout')
    ->assertSuccessful();

$this->assertCount(0, $user->fresh()->tokens);

$this->withHeaders(['Authorization' => "Bearer {$token}"])
    ->json('GET', 'api/status')
    ->assertUnauthorized();

There is still a request()->user() accessible in the second call

This means that assertUnauthorized fails

Route::get('api/auth/logout', function() {
    $user->tokens->each->delete();
});
Route::get('api/status', function() {
    dd(request()->user()); // should be null but isnt
});

Adding signature to the token value

When the tokens are created, they're generated as hashed of a random string (based on the code in Str::random it's from random_bytes which is good). However, this also leaves them open to possible brute force attempts as a persistent attacker could start guessing hash values in the sha256 space trying to locate a valid token value.

I'd suggest that a "secret" value be added for the token such that it can be used in an HMAC hashing process for the token to help prove that the token came from the application it was signed by. This wouldn't 100% prevent the brute forcing of the token but it would reduce the risk of an attacker just guessing the hash value.

Here's the proposal:

For generation:

  1. Generate the hash as it's currently done (a sha256 hash, always 256 bits long)
  2. Use the secret value to generate the HMAC signature of the hash (sha512 would be a good choice here`)
  3. Concatenate the two hashes

For validation:

  1. Split the token at the 256 bits location to give the hash and the signature
  2. Validate the signature to ensure the token is from the same application.

Concatenating the values like this also has the benefit of increasing the entropy of the token returned to the requesting frontend as it's length is dramatically increased.

Suggestion: Adding a token timeout configuration option

I briefly looked through the code and didn't see anything that indicated that the tokens from this were ever expired. The problem with not expiring the tokens is that, if they were ever somehow captured (maybe an XSS in the site or some man-in-the-middle), they would work forever.

I'd suggest implementing some kind of default timeout on the tokens that the user could adjust to their liking. I can understand the argument of "the developer should invalidate the token when they choose too" but that's not a secure by default approach. Given that this is a security control, I'd recommend at least allowing this kind of value to be set.

[Question] Why is referer header used instead of getHost()?

If I want to support both cookie-based and token based auth, I would dedicate different domans per each auth method, e.g. request to mysite.com should be guarded by cookies and sessions and csrf tokens, while request to myapp.com should be guarded by bearer token, with no session middleware and csrf token. So I am confused why this project is using referer header instead of request()->getHost() or $_SERVER['HTTP_HOST']?

Session authentication from any domain

Hello!

First of all - thanks for the package! And to the issue...

In airlock documentation it's said that

Airlock will only attempt to authenticate using cookies when the incoming request originates from your own SPA frontend.

I thinks that's a bit misleading. Actually airlock will attempt to authenticate using session cookie when referer header with your first-party domain is sent - which can be easily done from any domain or server (with GuzzleHttp for example).

Because of that you can't actually be sure that requests sent from third-party domains are authenticated using authorization token and not a session. So you can't rely on number of features (such as limiting requests count based on user api token and so on, because user always can exploit session authentication).

So what do you guys think? Is there any way to be sure that we are authenticated with authorization token? Should the possibility of changing referer and authenticate with session from any domain be mentioned in documentation?

Not enough integration with Passport

So I'm actually using passport to authenticate my entire API. However, I've now reached the point where I actually need stateful authentication for a first-party front-end.

I found airlock as a possible solution, but I don't understand how I'm supposed to use airlock and passport together, and I think this is down to airlock being in development and has unfinished or unclear documentation. (or quite possibly, I'm being dumb)

So using passport, my User model already uses the passport's equivalent to HasApiTokens trait. So I'm assuming I just ignore adding the airlock equivalent - but I'm unsure, I think this could do with some clarification.

Finally, in my AuthController I have a login method which already creates a personal access token and returns it in a JSON response back to the user, now I'm assuming I'm supposed to include the Auth facade upon successful authentication and use the login method to create the session. So my questions around this premise are :-

  • Does Laravel automatically know which driver to use?
  • Does it know to use the airlock driver when creating my session instead of the passport driver, if so can this be explained how? (not required but appreciated!)
  • How are the CSRF tokens validated? I see I create a GET request, but this doesn't return anything, am I expected to pass the token through or is this automatically set for me? does this mean I need to add the CSRF protection to my API routes? if so, what does this mean for my routes that are stateless?

Clarification would be helpful! thank you.

Add prefix key to config file

In this commit @taylorotwell added the prefix option for the airlock routes.

I personally add the prefix api to all my api calls.

A small but helpful enhancement would be to add to prefix key to the config file by default!

Below a snipped for the config file.

/*
|--------------------------------------------------------------------------
| Airlock Route Prefix
|--------------------------------------------------------------------------
|
| This is the place to add a prefix to the Airlock routes. Feel free to
| change the default prefix to anything you like. For example to add api
| prefix before every api call made to Airlock routes
|
*/

'prefix' => 'airlock',

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))
  })
})

[Feature Request] Expiration based off token name

Allow the expiration option to accept an array of the token names so you can set specific timeouts based on type of token. Web app, mobile app etc.

You could've the ability to set the config like this:

'expiration' => [
    'token-name' => null,
    'web-app' => null,
    'mobile-app' => null,
],

Support apps without a domain

I saw the domain verification is based on the referer header, but some apps, such as mobile apps, don't have a domain. Maybe the package should support an option to not verify the domain, something like * domain.

Integration with Laravel Spark

After weeks of struggling to get Passport to work with my SPA, I return to Laravel Airlock to find it "just works", so thank you for that 🤗

My question is in regards to integrating Airlock with Spark install. I did Airlock first, then did manual install of Spark which overwrote some things (and had issues with tables already created). I can go in and manually fix, but I wonder if it would be helpful to have official documentation as to how to get the two to work nicely together (as they're both part of Laravel).

HasApiTokens tokens() method does not return token

In my login controller I am using this code to log in the user

$credentials = $request->only('email', 'password');
        if (Auth::attempt($credentials)) {
            return Auth::user()->tokens()->first();
        }

and the result is like this without the token field:

{
    "id": 5,
    "user_id": 6,
    "name": "auth",
    "abilities": [
        "*"
    ],
    "last_used_at": "2020-01-10 18:21:19",
    "created_at": "2020-01-10 18:21:14",
    "updated_at": "2020-01-10 18:21:19"
}

Is there something that I missed or mistakenly used?

Unable to change route path

By default, the package loads the route into /airlock/csrf-cookie.

Since the application constantly accesses only the /api routes, I changed the parameter baseURL to axios.defaults.baseURL = '/api';

Now when you try to send a GET request to address /airlock/csrf-cookie, in fact the request is sent to /api/airlock/csrf-cookie.

It would be great to do one of the following options:

  1. add the ability to specify the route prefix in file config/airlock.php;
  2. change the route declaration method similar to Passport::routes().

Highlight existence of $user->currentAccessToken()

While fully fledged documentation may not be a priority at the moment I just wanted to raise this as a half thank you and half "please make others aware of the existence of this feature" issue.

Using Passport I had to do all this just to be able to log a user out:

class UsersController extends Controller
{
    /**
     * The token repository implementation.
     *
     * @var \Laravel\Passport\TokenRepository
     */
    protected $tokenRepository;

    /**
     * Create a controller instance.
     *
     * @param  \Laravel\Passport\TokenRepository  $tokenRepository
     * @return void
     */
    public function __construct(TokenRepository $tokenRepository)
    {
        $this->tokenRepository = $tokenRepository;
    }

    /**
     * @param  Request  $request
     * @return Response
     */
    public function logout(Request $request)
    {
        $token = $request->bearerToken();
        $token_id = (new \Lcobucci\JWT\Parser())->parse($token)->getHeader('jti');
        $token = $this->tokenRepository->findForUser(
            $token_id,
            $request->user()->getKey()
        );
        $token->revoke();
        $delete_cookie = Cookie::forget(Passport::cookie());
        return response()->noContent()->withCookie($delete_cookie);
    }
}

and with Airlock this seemingly is just reduced to

class UsersController extends Controller
{
    /**
     * @param  Request  $request
     * @return Response
     */
    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();
        return response()->noContent();
    }
}

which is a huge improvement both in terms of readability and the amount of reverse engineering needed to achieve this. I would like to suggest that the existence of this method of the Laravel\Airlock\HasApiTokens trait be featured in the documentation to make sure nobody misses this, as I think this is probably my favorite addition by Airlock yet.


I originally started this issue by asking for this feature to be implemented, but when I went to check the source, sure enough it already was! Hence why I suggest highlighting it instead.

Add support to disable update the last used

Motivation

On environment with many requests, updating the last used field at every requests adds a lot of load on database. Especially when you have a master slave replication.
In our scenario that field is not used at all.

By disabling the update we gain 20% more throughput

return $this->supportsTokens($accessToken->tokenable) ? $accessToken->tokenable->withAccessToken(
                //tap($accessToken->forceFill(['last_used_at' => now()]))->save()
                $accessToken
            ) : null;

I am not a Laravel developer, so I can't submit a PR.

Question: is there a reason that session.driver is forced to cookie?

A teammate and I were stumped as to why the session from our web-based login was not available when making API requests with the provided middleware. After awhile, we realised that our session driver was set to database (which is preferable to us), and the middleware enforces the cookie driver.

Simply removing the session.driver = cookie section from the middleware works, but I'm assuming there is a reason it is set up this way? To my understanding, the session id is stored as an encrypted cookie anyway (withEncryptCookies and StartSession middleware in the pipeline), and it's simply the data stored within the session that is affected by the configureSecureCookieSessions method.

Any thoughts?

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

Unable to exclude URIs from CSRF verification

  • Airlock Version: 0.1.0
  • Laravel Version: 6.9.0
  • PHP Version: 7.4.0
  • Database Driver & Version: MySQL 5.7

Description:

I can't exclude URIs from CSRF verification because of this LoC
Laravel Airlock is using the middleware from the Illuminate package instead of the local one.
This way the $except remains always an empty array, and I can't exclude URIs.

Steps To Reproduce:

  1. Add URIs to the $except array in App\Http\Middleware\VerifyCsrfToken.php file.
  2. Try to access this route without a CSRF token.

Suggestion

Add to the config/airlock.php file a configuration variable:

'csrfMiddleware` => App\Http\Middleware\VerifyCsrfToken::class,

And make sure to use it in the EnsureFrontendRequestAreStateful:

static::fromFrontend($request) ? [
  \Illuminate\Cookie\Middleware\EncryptCookies::class,
  \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
  \Illuminate\Session\Middleware\StartSession::class,
  Config::get('airlock.csrfMiddlewareClass', \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class),
: []

How save token in browser

Hello,
Before everything we are happy that @taylorotwell make this package.

1.After i use airlock for login it redirect to /home which is incorrect and i wanto redirect to $redirectTo.
2.Should we save token in localstoeage?
3.How can i send Bearer to server?

@taylorotwell I think we need full example for this package.

Handling for when Accept header not passed

  • Airlock Version: Latest
  • Laravel Version: Latest
  • PHP Version: 7.4 FPM
  • Database Driver & Version: MySQL 8

Description:

Is there a better way to handle this route not found error 500 issue.

If I have a route:

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

Then let's say a random user visits /user not in the "api calling way" of the SPA passing the header, surely we don't want to throw a 500 error by default? There must be a better way to handle this to return another form of error. 500 status code doesn't suffice and obviously I don't have a login page/route by default.

Steps To Reproduce:

Route [login] not defined thrown when the Accept header is not passed as application/json (Yes it would and should be passed like this).

Flare Trace:

https://flareapp.io/share/353da6mW#F31

Opinions on this? This is just a clean install from the package and framework. So curious to see how people handle for this or if we can have a solution. Hope this makes sense if not let me know.

Mark Laravel 6.* dependency to 6.9.0 or higher

I just tried to install Airlock into a project that was on 6.3.0 and found it didn't work. Having looked into the issue Airlock requires at least 6.9.0 to work due to the use of \Illuminate\Foundation\Http\Kernel::prependToMiddlewarePriority(); in Laravel\Airlock\Air\AirlockServiceProvider::configureMiddleware() on line 109.

I would suggest that the composer json be updated or that a check be added for lower versions without the method to avoid calling it and making it clear in a doc that anything pre 6.9.0 requires the middleware to be assigned manually.

Happy to make the changes myself and PR them it's agreed to be worthwhile.

'tokenable_id' cannot be null

I am using airlock for authentication and when i try to create a token it gives me this error

Integrity constraint violation: 1048 Column 'tokenable_id' cannot be null (SQL: insert into personal_access_tokens (name, token, abilities, tokenable_id, tokenable_type, updated_at, created_at) values ([email protected], 00f23c417988d8fef36a6275db0a6346acfe6c14004f4bc0d086d9a6249e4e0f, ["*"], ?, Modules\User\Entities\User, 2020-02-18 12:46:10, 2020-02-18 12:46:10))

Any idea why this happen ?

I am using Laravel Framework 6.15.0

Method for getting token with specific name

I've created a simple method in HasApiTokens.php to get the token with specified name:

    public function tokenWithName($name)
    {
        return optional($this->tokens()->where('name', $name)->first())->token;
    }

It might be useful when we have multiple tokens with different names for the same user and want to get a specific one.
The problem is the token is the hashed one not the plaint text and it seems it cannot be used to authenticate with route /user when sending the hashed token, it works only with the plain text one, probably because in Guard.php is this line:
$accessToken = $model::where('token', hash('sha256', $token))->first();

usePersonalAccessTokenModel more described

Hello,

This is in the docs:

Customization

You may customize the personal access token model used by Airlock via the usePersonalAccessTokenModel methods. Typically, you should call this method from the boot method of your AppServiceProvider:

use App\Airlock\CustomPersonalAccessToken;
use App\CustomUser;
use Laravel\Airlock\Airlock;

public function boot()
{
    Airlock::usePersonalAccessTokenModel(
        CustomPersonalAccessToken::class
    );
}

Looks promising, because in that way you can use a different Model then App/User for requests made with the Airlock Middleware, but the example is incomplete..

My expectation is when you got the usePersonalAccessTokenModel to work with a different custom Model that will result as the request()->user.

This code:

Route::middleware(‘auth:airlock’)->get(‘/name’, function (Request $request) {
    $user = $request->user(); // Expected Model to be: App\CustomUser
    return response()->json([‘name’ => $user->name]);
});

I expect that the $user is of a Model-type: App\CustomUser, but it isn't.

Consider unique constraint on `user_id` and `name`

I feel there is a benefit to adding a unique constraint across the columns user_id and name.

Currently users can create multiple tokens with the same name, meaning differentiating between them at a later date would be impossible as the key is only to be shown once.

Config issue sharing session between web and api

Because there's no auth scaffolding to use this at the moment (that I know of anyway), I just left the auth using the standard auth scaffolding.

I ended up having an issue using the session after logging in using the web guard because of my session driver config, it was set to "file" in my .env. I realised that it's set to "cookie" in the Airlock middleware, so once I changed that to match in my .env all was good. But it could be helpful to have a note about this.

Using auth's config user model only

Just posing the thought,

When browsing the code here, it looks like if you declare a user model via useUserModel that it will only take effect if the auth.providers.users.model is null. Which it wouldn't ever be right?

I wonder if it's safe to assume that auth.providers.users.model is always the value desired for this action and that it can bypass the need for the useUserModel flexibility you're after.

If removed, maybe the PersonalAccessToken model could go in config/airlock.php
When someone vendor publishes its all there and don't have to add in a service provider.

Maybe adding the user model to airlock's config too if can't rely on auth.php for some reason

CSRF Token mismatch subdomain

  • Airlock Version: 0.2.1
  • Laravel Version: 6.2
  • PHP Version: 7.4.2
  • Database Driver & Version: Mysql & 8.0.19

I am trying to login using the package and I was successful with Vue running on laratesting:8080 and laratesting:8081 it logins, gives the correct csrf tokens and subsequent requests are working fine. What I am trying to achieve,
API: api.laratesting
Vue: app.laratesting

I am sending a request to laravel from app.laratesting to api.laratesting. Cookies are returned but not set.
with SESSION_DOMAIN=.laratesting

This set-cookie domain attribute was invalid with regards to the current host url
with SESSION_DOMAIN=null
This set-cookie didn't specify a samesite attribute

Am I doing something wrong or should I stick to access_tokens ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.