Giter Site home page Giter Site logo

codecasts / laravel-jwt Goto Github PK

View Code? Open in Web Editor NEW
234.0 21.0 27.0 59 KB

Dead simple, plug and play JWT API Authentication for Laravel (5.4+)

License: MIT License

PHP 100.00%
laravel laravel-5-package jwt jwt-authentication jwt-auth json-web-token laravel-54

laravel-jwt's Introduction

Readme Art

Laravel JWT

Latest Stable Version Total Downloads License

This package provides out-of-the-box API authentication using JWT for Laravel.

Installation.

You can install this package by running:

composer require codecasts/laravel-jwt

Setup.

In order to setup this package into your application, minimal configuration is actually needed.

1) Service Provider.

Register this package's Service Provider by adding it to the providers section of your config/app.php file:

You may skip this step on Laravel 5.5 due to the auto-discovery package feature.

   'providers' => [

       // ... other providers omitted

       Codecasts\Auth\JWT\ServiceProvider::class,

   ],

2) Configuration file.

Publish the configuration file (config/jwt.php) by running the following command after registering the Service Provider.

php artisan vendor:publish --provider="Codecasts\Auth\JWT\ServiceProvider"

3) Generate a Secret.

In order for this package to works, you will need a separate secret (do not use the application key).

This package provides a command that can be used for generating a strong key.

Get a new key by running:

php artisan jwt:generate

Then, copy the generated key contents into your .env file.

NOTICE: The key generation process will not automatically set it inside your .env file, do it manually.

4) Setup Guard

In order to automatically authenticate your routes using JWT tokens, you need to change the guard driver to jwt

Inside config/auth.php set the corresponding guard group you want to protect:

If you have the default guard group named api, your auth.php should be like this:

  'guards' => [
        // ... other guards omitted.

        'api' => [
            'driver'   => 'jwt', // this is the line you need to change.
            'provider' => 'users',
        ],
    ],

That's it, we are all ready to use it.

Usage.

This package aims to be dead simple to use.

The following templates can be used to setup your existing authentication controllers and resources.

NOTICE: Full working examples of use for this package will be added on this package when it reaches it's 1.0 version.

Protecting Routes.

This package is fully integrated with Laravel Authentication.

The default configuration (config/jwt.php) brings a sensitive value that is very useful when your application is not completely an API: middleware_match

By not completely an API, I mean, the JWT guard is not the default one.

In those cases, in order to use the auth middleware, the config key middleware_match MUST be set to true.

This configuration key allows non protected routes to work properly.

Notice that this option will match middleware group names with guard names.

In this case, the 'api' middleware group will always use the api guard.

Also, the 'web' middleware group will always use the web guard

If you do not use this value, you will need to use suffixes when referencing the auth middleware, like auth:api.

Issuing and Renewing Tokens.

For issuing tokens, no special class is actually needed, you can just expect create a Guard current implementation from the IoC and work from there.

Check out the examples.

On the following examples, all Guard instances are injected from Illuminate\Contracts\Auth\Guard

On the following examples, all Request instances are injected from Illuminate\Http\Request

Token from User Instance.

This method should be used when you just registered a user and any other special cases.

public function tokenFromUser(Guard $auth)
{
    // generating a token from a given user.
    $user = SomeUserModel::find(12);

    // logs in the user
    $auth->login($user);

    // get and return a new token
    $token = $auth->issue();

    return $token;
}

Token from User Credentials.

This method should be used when you just registered a user and any other special cases.

public function tokenFromCredentials(Guard $auth, Request $request)
{
    // get some credentials
    $credentials = $request->only(['email', 'password']);

    if ($auth->attempt($credentials)) {
       return $token = $auth->issue();
    }

    return ['Invalid Credentials'];
}

Refreshing Tokens.

Tokens can be refreshed in 2 different ways: Auto detect or manual.

If you do not pass any argument into the refresh method, the Guard will look for either a Authorization header or a token field on the request's body.

public function refreshToken(Guard $auth)
{
    // auto detecting token from request.
    $token = $auth->refresh();

    // manually passing the token to be refreshed.
    $token = $auth->refresh($oldToken);

    return $token;
}

Custom Claims.

Of course, there are support for custom claims.

You can set them in two ways.

By explicitly passing them.

$customClaims = [
    'custom1' => 'value1',
    'custom2' => 'value2',
];

// when issuing
$auth->issue($customClaims);

// when refreshing
// custom claims are the second parameter as the first one is the
// old token
$auth->refresh(null, $customClaims);

By Authenticatable method.

If all your users will have the same custom claims, you can setup a default custom claims method on your User's model (or any other Authenticatable you're using):

If the method customJWTClaims() is present on the model being issue the token against, this claims will be automatically included.

class User extends Model implements Authenticatable
{
    public function customJWTClaims()
    {
        return [
            'email' => $this->email,
            'name'  => $this->name,
        ];
    }
}

Contributing

Please see CONTRIBUTING for details.

laravel-jwt's People

Contributors

adrianogl avatar emtudo avatar flyingluscas avatar hernandev avatar jonagoldman avatar jvlppm avatar mateusjatenee avatar motia 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

laravel-jwt's Issues

manual .env key

Hi,
im new to laravel and im learning.
after a bad test with the outdate 0.5 tymothy package, i found this one.
it automagic installed, and that was great :)

but is there any specific issue to not write the generated key to the .env file?

Repository abandoned?

Seems like this project is not maintained anymore?

The last couple of issues had a response like "Will fix this today" but both branches did not have any changes accordingly.

if you Google for "Laravel jwt" this package is quite high up in the ranking, so maybe add a notice about it not being ready to use ?

Would you allow me to fork this repository? because its 80% of what i need, and i dont feel like writing it from scratch if i don't have to.

  • Xantios

Erro no vendor:publish

Ao executar php artisan vendor:publish --provider="Codecasts\Auth\JWT\ServiceProvider", surge a seguinte mensagem: Can't locate path: <0>
Publishing complete.

E não cria o arquivo de configuração em config.

Laravel 5.4.*
PHP 7.1
Ubuntu 16.04

Don't forget config:clear!

A quick word about a problem I faced while deploying on Production.

Don't forget to clear your config cache if you use php artisan config:cache and all these optimizations commands.

php artisan config:clear

I lost some precious time trying to understand what didn't work as config/auth.php needs to be modified.

That's all, mates. Take care.

Find user by a combination of parameters or validate token in a different way (possible security issue)

Looking inside the Guard, I see that the token is validated and then the user is retrieved by id:

// Codecasts\Auth\JWT\Auth\Guard

protected function findUserByToken(Token $token)
{
    // retrieves the user ID from the token.
    $id = $token->getClaim('sub');

    // use the users provider to find the token subject (user) but it's id (subject)
    return $this->provider->retrieveById($id);
}

But I have a security problem:

I use multiple databases (for a multi tenant Saas application), one database per tenant, each database have its own users table. When the application start, I select the correct database connection based on a custom 'Tenant' header.

The problem is that I have many users with the same id, because they come from different databases, so the same token is valid for all users with the same id. This causes that one user can login into another database just by changing the 'Tenant' header.

I need a way to validate the token or select the user in a different way, taking into consideration the 'Tenant' header.

Any ideas? Thanks.

Package autodiscovery

Hi @hernandev!
I`m using your package with Laravel 5.5 and, despite the fix in PR #17, I was able to use it by manually adding a secret to the config file.

My question is: can I make a PR to add package autodiscovery, or should I wait until PR #17 is closed?

Decode token

How do I decode a token getting by Auth::getToken()?
Is there any other way to get decoded token?

\Illuminate\Auth\Events\Login not firing

Not detecting the \Illuminate\Auth\Events\Login event. This should be true for all auth events (I havent tested them) as the Codecasts\Auth\JWT\Auth\Guard::$events is not set.

Possible solution is to change the constructor but think it should be set by the framework somewhere.

    /**
     * JWT Guard constructor.
     *
     * @param \Illuminate\Contracts\Foundation\Application $app
     * @param string $name
     * @param \Illuminate\Contracts\Auth\UserProvider $provider
     * @param \Codecasts\Auth\JWT\Contracts\Token\Manager $manager
     */
    public function __construct($app, $name, $provider, $manager)
    {
        // assign constructor arguments into instance scope.
        $this->app = $app;
        $this->name = $name;
        $this->provider = $provider;
        $this->manager = $manager;
        $this->setDispatcher($this->app['events']); //add this to ensure $events has properly populated dispatcher
    }

302 Redirect on Expired Token?

Am I missing something?

Using this with Laravel 5.5, testing expired tokens.

Set the timeout to 1 minute.

Works before it times out, then after 1 minute when I make the call, rather than returning a 401 "Expired Token" it does a 302 redirect to /auth/login

Am I crazy or is something not working right there?

Bearer Token and query parameter conflict

I do use the authorization header with a valid jwt token,
but if one of my routes also expects a token parameter (device token registration, for instance)

the query token is used instead as an authentication token, and the authorization header is ignored.

Method issue() does not exist.

I follow the instructions step by step, but throw Exception
Method issue() does not exist.
Any Idea what is wrong?

My code:

function login(Guard $auth){
$user2 = User::find(1);
$auth->login($user2);
$token = $auth->issue();
return $token;
}

How to logout/blacklist

I can call $guard->logout() successfully, but then I can use that same token for the user I just logged out to call authenticated routes afterwards.

Looking at the function, it doesn't look like it's doing anything. Has this been implemented yet?

Contributing guide

Hi @hernandev, me again hehe, I think it would be very good if this project had a contributing guide so that other developers don't make the same mistake I did when I've opened the PR #18, sending to the master branch instead of develop, what you think?

Error: KeyGenerateCommand::handle() does not exist

When running php artisan jwt:generate get the following error:

ERROR: Method Codecasts\Auth\JWT\Console\KeyGenerateCommand::handle() does not exist {"exception":"[object] (ReflectionException(code: 0): Method Codecasts\\Auth\\JWT\\Console\\KeyGenerateCommand::handle() does not exist

Using: laravel/framework (v5.5.12) & codecasts/laravel-jwt (0.8.5)

Can this be used with multiple guard?

Not exactly an issue, but had to ask this question. Can this be used with multiple guards? If yes then how to configure it?

In my config/auth.php

    'guards' => [
        'user' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],

        'staff' => [
            'driver' => 'jwt',
            'provider' => 'staff',
        ],
    ],

I am trying to do something like this.

jwt:generate not working

Hi,

I found small bug. When I try run command php artisan jwt:generate then I get this error:

[ReflectionException]
  Method Codecasts\Auth\JWT\Console\KeyGenerateCommand::handle() does not exist

PS. I executed composer dump-autoload before.

Could you fix it?

Resolve user for token

If I have a token, how can I retrieve the user for the token?

I've found findUserByToken but it's a protected method.

Authenticating with a token seems like basic functionality.

Cheers.

Typo in readme.md?

Token from User Credentials.

This method should be used when you just registered a user and any other special cases.

I think this should be "This method should be used when you want to authenticate a user and any other special cases." because the function

public function tokenFromCredentials(Guard $auth, Request $request)
{
    // get some credentials
    $credentials = $request->only(['email', 'password']);

    if ($auth->attempt($credentials)) {
       return $token = $auth->issue();
    }

    return ['Invalid Credentials'];
}

really looks like the one in https://laravel.com/docs/5.6/authentication#authenticating-users section.

public function authenticate(Request $request)
{
    $credentials = $request->only('email', 'password');

    if (Auth::attempt($credentials)) {
        // Authentication passed...
        return redirect()->intended('dashboard');
    }
}

Genarate token for never expirate

Hi folks,

I've implemented this lib in my project, but i had a problem: i want to generate a token that never expires, but i haven't found a way to do it

thanks

Allow to change secret key before or after Manager initialization

I want to have multiple secret keys for better security (related to #25).
In my application each tenant have a secret key saved in the database, so I need a way to change the key set in Codecasts\Auth\JWT\Token\Manager.

I tried to change the config inside a middleware:

Config::set('jwt.secret', $tenant->jwt_secret);

but the Manager is initialized before the middleware runs, so the change is irrelevant.

I need a way to change the key in the config before the Manager is initialized or a way to change the key afterwards.

BindingResolutionException

After installation strictly according to the instructions, I have a exception:

Unresolvable dependency resolving [Parameter #0 [ $app ]] in class Codecasts\Auth\JWT\Auth\Guard in Container.php (line 910)

Laravel 5.4.28

I did:

  1. composer require codecasts/laravel-jwt
  2. added service provider Codecasts\Auth\JWT\ServiceProvider::class
  3. published vendor files
  4. generated and added secret to .env
  5. changed driver in api guards to 'jwt'

Adding RS-256/512 JWT signature methods

I see the default (and only) option with this library is HS-256.

That's a perfectly viable option, but I'm curious to know if you've considered adding support RS-256 or RS-512 key pairs?

I really like the simplicity this library affords; seeing these added would be great.

Is this production ready?

Was looking for a Tymon JWT alternative and found this repo. Looks nice but noticed, for example, that logout functionality is not implemented. So I was wondering if this repo is ready for production or are there any other unknown unfinished parts? Thanks.

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.