├── .gitignore ├── LICENSE ├── README.md ├── composer.json ├── config └── jwt.php ├── src └── MiladRahimi │ └── LaraJwt │ ├── Exceptions │ ├── InvalidJwtException.php │ └── LaraJwtConfiguringException.php │ ├── Facades │ └── JwtAuth.php │ ├── Guards │ └── Jwt.php │ ├── Providers │ └── ServiceProvider.php │ └── Services │ ├── JwtAuth.php │ ├── JwtAuthInterface.php │ ├── JwtService.php │ └── JwtServiceInterface.php └── tests ├── Classes ├── Person.php └── SomeException.php ├── JwtAuthTest.php ├── JwtGuardTest.php ├── JwtServiceTest.php └── LaraJwtTestCase.php /.gitignore: -------------------------------------------------------------------------------- 1 | /vendor 2 | /composer.lock 3 | /.idea 4 | .idea/php.xml -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Milad Rahimi 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LaraJwt 2 | Laravel JWT guard and authentication tools 3 | 4 | > This package is no longer maintained. 5 | > You can use the [laravel/passport](https://github.com/laravel/passport) package instead. 6 | > Or you may use [miladrahimi/php-jwt](https://github.com/miladrahimi/php-jwt) to create your custom jwt guard. 7 | 8 | ## Documentation 9 | 10 | ### Overview 11 | 12 | LaraJwt is a Laravel package for generating JWT (JSON Web-based Token) from users and providing JWT guard for Laravel 13 | applications. 14 | 15 | ### Installation 16 | 17 | Add the package via Composer: 18 | 19 | ``` 20 | composer require miladrahimi/larajwt:2.* 21 | ``` 22 | 23 | Then run the following command to generate `jwt.php` (the package config) in your Laravel config directory: 24 | 25 | ``` 26 | php artisan vendor:publish --tag=larajwt-config 27 | ``` 28 | 29 | #### Notes on Installation 30 | 31 | * The package service provider will be automatically discovered by Laravel package discovery. 32 | 33 | * The `JwtAuth` alias for `MiladRahimi\LaraJwt\Facades\JwtAuth` will be automatically registered. 34 | 35 | ### Configuration 36 | 37 | To configure the package open `jwt.php` file in your laravel config directory. This files consists of following items: 38 | 39 | * `key`: The secret key to sign the token, it uses your project key if you leave it empty. 40 | * `ttl`: Time that token will be valid, token will be expired after this time (in seconds) 41 | * `issuer`: Issuer claim 42 | * `audience`: Audience claim 43 | * `model_safe`: Set it true if you have different authentication for different models with LaraJwt, it ensures that 44 | token belongs to related model defined in guard. 45 | 46 | ### Generate JWT from Users 47 | 48 | Use the method below to generate JWT from users or any other authenticable entities (models): 49 | 50 | ``` 51 | $jwt = JwtAuth::generateToken($user); 52 | ``` 53 | 54 | For example you may generate JWT from users in the sign-in process like this: 55 | 56 | ``` 57 | $credential = [ 58 | 'email' => $request->input('email'), 59 | 'password' => $request->input('password'), 60 | ]; 61 | 62 | if(Auth::guard('api')->attempt($credential)) { 63 | $user = Auth::guard('api')->user(); 64 | 65 | $jwt = JwtAuth::generateToken($user); 66 | 67 | // Return successfull sign in response with the generated jwt. 68 | } else { 69 | // Return response for failed attempt... 70 | } 71 | ``` 72 | 73 | If you want to store more information like role in the token, you can pass them to the method this way: 74 | 75 | ``` 76 | $customClaims = ['role' => 'admin', 'foo' => 'bar']; 77 | 78 | $jwt = JwtAuth::generateToken($user, $customClaims); 79 | ``` 80 | 81 | ### Guards 82 | 83 | Add as many as guard you need in your `config/auth.php` with `jwt` driver like this example: 84 | 85 | ``` 86 | 'guards' => [ 87 | 'web' => [ 88 | 'driver' => 'session', 89 | 'provider' => 'users', 90 | ], 91 | 92 | 'api' => [ 93 | 'driver' => 'jwt', 94 | 'provider' => 'users', 95 | ], 96 | ], 97 | ``` 98 | 99 | ### Authenticated Routes 100 | 101 | After configuring guards in `config/auth.php` you can protect routes by the defined guards. 102 | 103 | In our example we can protect route like this: 104 | 105 | ``` 106 | Route::group(['middleware' => 'auth:api'], function () { 107 | // Routes... 108 | }); 109 | ``` 110 | 111 | * Your clients must send header `Authorization: Bearer ` in their requests. 112 | 113 | ### Authenticated User 114 | 115 | To retrieve current user and his info in your application (controllers for example) you can do it this way: 116 | 117 | ``` 118 | // To get current user 119 | $user = Auth::guard('api')->user(); 120 | $user = Auth::guard('api')->getUser(); 121 | 122 | // To get current user id 123 | $user = Auth::guard('api')->id(); 124 | 125 | // Is current user guest 126 | $user = Auth::guard('api')->guest(); 127 | 128 | // To get current token 129 | $jwt = Auth::guard('api')->getToken(); 130 | 131 | // To get current token claims 132 | $claims = Auth::guard('api')->getClaims(); 133 | 134 | // To get a sepcific claim from current token 135 | $role = Auth::guard('api')->getClaim('role'); 136 | 137 | // Logout current user (JWT will be cached in blacklist and NOT valid in next requests). 138 | Auth::guard('api')->logout(); 139 | 140 | // Logout current user (but it will be VALID next reuqests). 141 | // It clears caches so user will be fetched and filters will be executed again in next request. 142 | Auth::guard('api')->logout(false); 143 | ``` 144 | 145 | Since LaraJwt caches user fetching it can authenticate users without touching database. 146 | 147 | ### Retrieve User Manually 148 | 149 | You may need to retrieve user from generated JWTs manually, no worry! just do it this way: 150 | 151 | ``` 152 | $user = JwtAuth::retrieveUser($jwt); 153 | 154 | ``` 155 | 156 | It uses default user provider to fetch the user, 157 | if you are using different provider you can pass it to the method as the second parameter like this: 158 | 159 | ``` 160 | $admin = JwtAuth::retrieveUser($jwt, 'admin'); 161 | ``` 162 | 163 | ### Retrieve JWT Claims Manually 164 | 165 | You my even go further and need to retrieve JWT claims manually, it has considered too. 166 | 167 | ``` 168 | $claims = JwtAuth::retrieveClaims($jwt); 169 | ``` 170 | 171 | The mentioned method returns associative array of claims with following structure: 172 | 173 | ``` 174 | [ 175 | 'sub' => '666', 176 | 'iss' => 'Your app name', 177 | 'aud' => 'Your app audience', 178 | // ... 179 | ] 180 | ``` 181 | 182 | ### Cache 183 | 184 | LaraJwt caches retrieving users process , so after first successful authentication it remembers jwt as long as ttl 185 | which is set in config, you may clear this cache to force LaraJwt to re-run filters or re-fetch user model from 186 | database, to do so you can use the this method: 187 | 188 | ``` 189 | JwtAuth::clearCache($user); 190 | ``` 191 | 192 | You can pass user model (Authenticable) or its primary key to the `clearCache` method. 193 | 194 | ### Filters 195 | 196 | Filters are runnable closures which will be called after parsing token and fetching user model. 197 | 198 | For example if you have considered boolean property like `is_active` for users, 199 | you probably want to check its value after authentication and raise some exception if it is false or change LaraJwt 200 | normal process the way it be seemed authentication is failed. 201 | 202 | You can register filters as many as you need, LaraJwt runs them one by one after authentication. 203 | 204 | AuthServiceProvider seems a good place to register hooks. 205 | 206 | ``` 207 | class AuthServiceProvider extends ServiceProvider 208 | { 209 | // ... 210 | 211 | public function boot() 212 | { 213 | // ... 214 | 215 | $jwtAuth = $this->app->make(JwtAuthInterface::class); 216 | 217 | // Check if user is active or not 218 | $jwtAuth->registerFilter(function (User $user) { 219 | if ($user->is_active == true) { 220 | return $user; 221 | } else { 222 | return null; 223 | } 224 | }); 225 | } 226 | } 227 | ``` 228 | 229 | The `registerFilter` takes a closure with one argument to get authenticated user and it should return the user if there 230 | is no problem, it can return null if you want make the authentication failed. 231 | 232 | ### Logout and JWT Invalidation 233 | 234 | As mentioned with example above you can logout user with following method: 235 | 236 | ``` 237 | Auth::guard('api')->logout(); 238 | ``` 239 | 240 | It takes one boolean parameter that is true in default and put the jwt in cached blacklist so the token won't be valid 241 | in next requests, but you can pass false to make it only logout current user and clear cache. 242 | 243 | You can also invalidate tokens with `JwtAuth` facade and `jti` claim this way: 244 | 245 | ``` 246 | JwtAuth::invalidate($jti); 247 | ``` 248 | 249 | ### Exceptions 250 | 251 | ``` 252 | Exception Class: LaraJwtConfiguringException 253 | Exception Message: LaraJwt config not found. 254 | ``` 255 | 256 | This exception would be thrown if you had not published the package config (mentioned in Installation section). 257 | 258 | ### JWT vs Stored Tokens 259 | 260 | You may consider simple database-stored tokens as the alternative for JWT for authenticating, 261 | So we have provided some differences and comparison for you. 262 | 263 | #### Cons 264 | 265 | * More HTTP overhead, generated tokens are long. 266 | * Force logout is more complex and tricky (LaraJwt handles it for you). 267 | 268 | #### Pros 269 | 270 | * No need to database column for storing generated tokens. 271 | * No database touch if you only need user id. 272 | * Less database touch if you cache user fetching (LaraJwt does it for you). 273 | 274 | ### Contribute 275 | 276 | Any contribution will be appreciated :D 277 | 278 | ## License 279 | This package is released under the [MIT License](http://opensource.org/licenses/mit-license.php). 280 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "miladrahimi/larajwt", 3 | "description": "JWT authentication tools and guard for Laravel projects", 4 | "keywords": [ 5 | "JWT", 6 | "Laravel", 7 | "Guard", 8 | "Authentication", 9 | "API", 10 | "REST" 11 | ], 12 | "homepage": "http://miladrahimi.github.io/larajwt", 13 | "type": "library", 14 | "license": "MIT", 15 | "authors": [ 16 | { 17 | "name": "Milad Rahimi", 18 | "email": "info@miladrahimi.com", 19 | "homepage": "http://miladrahimi.com", 20 | "role": "Developer" 21 | } 22 | ], 23 | "support": { 24 | "email": "info@miladrahimi.com", 25 | "source": "https://github.com/miladrahimi/larajwt/issues" 26 | }, 27 | "require": { 28 | "php": ">=7.0", 29 | "lcobucci/jwt": "^3.2", 30 | "laravel/framework": "^5.5|^6|^7|^8" 31 | }, 32 | "autoload": { 33 | "psr-4": { 34 | "MiladRahimi\\LaraJwt\\": "src/MiladRahimi/LaraJwt/", 35 | "MiladRahimi\\LaraJwtTests\\": "tests/" 36 | } 37 | }, 38 | "require-dev": { 39 | "mockery/mockery": "~1.0", 40 | "orchestra/testbench": "^3.5" 41 | }, 42 | "extra": { 43 | "laravel": { 44 | "providers": [ 45 | "MiladRahimi\\LaraJwt\\Providers\\ServiceProvider" 46 | ], 47 | "aliases": { 48 | "JwtAuth": "MiladRahimi\\LaraJwt\\Facades\\JwtAuth" 49 | } 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /config/jwt.php: -------------------------------------------------------------------------------- 1 | 5 | * Date: 9/19/17 6 | * Time: 14:40 7 | */ 8 | 9 | return [ 10 | 11 | // Secret key to sign tokens 12 | 'key' => env('JWT_KEY', env('APP_KEY', 'your key')), 13 | 14 | // Token time-to-live in seconds (default 30 days) 15 | 'ttl' => 60 * 60 * 24 * 30, 16 | 17 | // Token issuer (your app name) 18 | 'issuer' => env('JWT_ISSUER', env('APP_NAME', 'your app')), 19 | 20 | // Token audience (your api customer) 21 | 'audience' => env('JWT_AUDIENCE', ''), 22 | 23 | // Set true if you have multiple authentication for multiple models 24 | // It ensures that token for a model won't be valid for another models 25 | 'model_safe' => false, 26 | 27 | ]; -------------------------------------------------------------------------------- /src/MiladRahimi/LaraJwt/Exceptions/InvalidJwtException.php: -------------------------------------------------------------------------------- 1 | 5 | * Date: 9/18/17 6 | * Time: 16:46 7 | */ 8 | 9 | namespace MiladRahimi\LaraJwt\Exceptions; 10 | 11 | use Exception; 12 | 13 | class InvalidJwtException extends Exception 14 | { 15 | // 16 | } -------------------------------------------------------------------------------- /src/MiladRahimi/LaraJwt/Exceptions/LaraJwtConfiguringException.php: -------------------------------------------------------------------------------- 1 | 5 | * Date: 11/3/2017 AD 6 | * Time: 22:47 7 | */ 8 | 9 | namespace MiladRahimi\LaraJwt\Exceptions; 10 | 11 | use Exception; 12 | 13 | class LaraJwtConfiguringException extends Exception 14 | { 15 | 16 | } -------------------------------------------------------------------------------- /src/MiladRahimi/LaraJwt/Facades/JwtAuth.php: -------------------------------------------------------------------------------- 1 | 5 | * Date: 11/2/2017 AD 6 | * Time: 20:04 7 | */ 8 | 9 | namespace MiladRahimi\LaraJwt\Facades; 10 | 11 | use Illuminate\Support\Facades\Facade; 12 | use MiladRahimi\LaraJwt\Services\JwtAuthInterface; 13 | 14 | class JwtAuth extends Facade 15 | { 16 | protected static function getFacadeAccessor() 17 | { 18 | return JwtAuthInterface::class; 19 | } 20 | } -------------------------------------------------------------------------------- /src/MiladRahimi/LaraJwt/Guards/Jwt.php: -------------------------------------------------------------------------------- 1 | 5 | * Date: 9/19/17 6 | * Time: 13:51 7 | */ 8 | 9 | namespace MiladRahimi\LaraJwt\Guards; 10 | 11 | use Illuminate\Auth\GuardHelpers; 12 | use Illuminate\Contracts\Auth\Authenticatable; 13 | use Illuminate\Contracts\Auth\Guard; 14 | use Illuminate\Contracts\Auth\UserProvider; 15 | use Illuminate\Http\Request; 16 | use MiladRahimi\LaraJwt\Services\JwtAuthInterface; 17 | 18 | class Jwt implements Guard 19 | { 20 | use GuardHelpers; 21 | 22 | /** @var Request $request */ 23 | protected $request; 24 | 25 | /** @var string $token */ 26 | protected $token; 27 | 28 | /** @var JwtAuthInterface $jwtAuth */ 29 | protected $jwtAuth; 30 | 31 | /** @var array $claims */ 32 | protected $claims = []; 33 | 34 | /** 35 | * Create a new authentication guard. 36 | * 37 | * @param UserProvider $provider 38 | * @param Request $request 39 | */ 40 | public function __construct(UserProvider $provider = null, Request $request = null) 41 | { 42 | $this->provider = $provider; 43 | $this->request = $request; 44 | 45 | $this->jwtAuth = app(JwtAuthInterface::class); 46 | 47 | $this->retrieveUser(); 48 | } 49 | 50 | /** 51 | * Retrieve user from jwt token in the request header 52 | */ 53 | private function retrieveUser() 54 | { 55 | $this->retrieveToken(); 56 | 57 | if ($this->getToken()) { 58 | $this->claims = $this->jwtAuth->retrieveClaims($this->getToken()); 59 | $this->user = $this->jwtAuth->retrieveUser($this->getToken(), $this->getProvider()); 60 | } 61 | } 62 | 63 | /** 64 | * Retrieve token from header 65 | */ 66 | private function retrieveToken() 67 | { 68 | $authorization = $this->request->header('Authorization'); 69 | 70 | if ($authorization && starts_with($authorization, 'Bearer ')) { 71 | $this->token = substr($authorization, strlen('Bearer ')); 72 | } 73 | } 74 | 75 | /** 76 | * Get current user JWT 77 | * 78 | * @return null|string 79 | */ 80 | public function getToken() 81 | { 82 | return $this->token; 83 | } 84 | 85 | /** 86 | * Validate a user's credentials. 87 | * 88 | * @param array $credentials 89 | * @return bool 90 | */ 91 | public function validate(array $credentials = []) 92 | { 93 | return $this->attempt($credentials, false); 94 | } 95 | 96 | /** 97 | * Attempt to authenticate the user using the given credentials and return the token. 98 | * 99 | * @param array $credentials 100 | * @param bool $login 101 | * 102 | * @return mixed 103 | */ 104 | public function attempt(array $credentials = [], $login = true) 105 | { 106 | $user = $this->provider->retrieveByCredentials($credentials); 107 | 108 | if ($this->hasValidCredentials($user, $credentials)) { 109 | return $login ? $this->login($user) : true; 110 | } 111 | 112 | return false; 113 | } 114 | 115 | /** 116 | * Determine if the user matches the credentials. 117 | * 118 | * @param mixed $user 119 | * @param array $credentials 120 | * 121 | * @return bool 122 | */ 123 | protected function hasValidCredentials($user, $credentials) 124 | { 125 | return $user && $this->provider->validateCredentials($user, $credentials); 126 | } 127 | 128 | /** 129 | * Create a token for a user. 130 | * 131 | * @param Authenticatable $user 132 | * 133 | * @return string 134 | */ 135 | public function login(Authenticatable $user) 136 | { 137 | $this->setUser($user); 138 | 139 | return $this->user(); 140 | } 141 | 142 | /** 143 | * Get the currently authenticated user. 144 | * 145 | * @return Authenticatable|null 146 | */ 147 | public function user() 148 | { 149 | return $this->user; 150 | } 151 | 152 | /** 153 | * Set the current request instance. 154 | * 155 | * @param Request $request 156 | * 157 | * @return $this 158 | */ 159 | public function setRequest(Request $request) 160 | { 161 | $this->request = $request; 162 | 163 | return $this; 164 | } 165 | 166 | /** 167 | * Return the currently cached user. 168 | * 169 | * @return Authenticatable|null 170 | */ 171 | public function getUser() 172 | { 173 | return $this->user(); 174 | } 175 | 176 | /** 177 | * Logout current user (And invalidate his/her JWT) 178 | * 179 | * @param bool $invalidateToken 180 | */ 181 | public function logout(bool $invalidateToken = true) 182 | { 183 | if ($this->user()) { 184 | if ($invalidateToken) { 185 | $this->jwtAuth->invalidate($this->getClaims()['jti']); 186 | } 187 | 188 | $this->jwtAuth->clearCache($this->user()); 189 | $this->user = null; 190 | $this->token = null; 191 | } 192 | } 193 | 194 | /** 195 | * Get all claims 196 | * 197 | * @return array 198 | */ 199 | public function getClaims(): array 200 | { 201 | return $this->claims; 202 | } 203 | 204 | /** 205 | * Get a specific claim 206 | * 207 | * @param string $name 208 | * @return mixed|null 209 | */ 210 | public function getClaim(string $name) 211 | { 212 | return $this->claims[$name] ?? null; 213 | } 214 | } -------------------------------------------------------------------------------- /src/MiladRahimi/LaraJwt/Providers/ServiceProvider.php: -------------------------------------------------------------------------------- 1 | 5 | * Date: 9/19/17 6 | * Time: 13:48 7 | */ 8 | 9 | namespace MiladRahimi\LaraJwt\Providers; 10 | 11 | use Illuminate\Support\ServiceProvider as Provider; 12 | use Lcobucci\JWT\Signer\Hmac\Sha512; 13 | use MiladRahimi\LaraJwt\Guards\Jwt as JwtGuard; 14 | use MiladRahimi\LaraJwt\Services\JwtAuth; 15 | use MiladRahimi\LaraJwt\Services\JwtAuthInterface; 16 | use MiladRahimi\LaraJwt\Services\JwtService; 17 | use MiladRahimi\LaraJwt\Services\JwtServiceInterface; 18 | 19 | class ServiceProvider extends Provider 20 | { 21 | /** 22 | * Register 23 | * 24 | * @return void 25 | */ 26 | public function register() 27 | { 28 | $this->app->singleton(JwtServiceInterface::class, JwtService::class); 29 | $this->app->singleton(JwtAuthInterface::class, JwtAuth::class); 30 | 31 | $this->app->bind('larajwt.signer', Sha512::class); 32 | } 33 | 34 | /** 35 | * Boot 36 | * 37 | * @return void 38 | */ 39 | public function boot() 40 | { 41 | // Extend laravel auth to inject jwt guard 42 | $this->app['auth']->extend('jwt', function ($app, $name, array $config) { 43 | 44 | $guard = new JwtGuard( 45 | $app['auth']->createUserProvider($config['provider']), 46 | $app['request'] 47 | ); 48 | 49 | $app->refresh('request', $guard, 'setRequest'); 50 | 51 | return $guard; 52 | }); 53 | 54 | // Install config on vendor:publish 55 | $this->publishes([ 56 | __DIR__ . '/../../../../config/jwt.php' => config_path('jwt.php') 57 | ], 'larajwt-config'); 58 | } 59 | } -------------------------------------------------------------------------------- /src/MiladRahimi/LaraJwt/Services/JwtAuth.php: -------------------------------------------------------------------------------- 1 | 5 | * Date: 11/2/2017 AD 6 | * Time: 19:59 7 | */ 8 | 9 | namespace MiladRahimi\LaraJwt\Services; 10 | 11 | use Closure; 12 | use Exception; 13 | use Illuminate\Auth\EloquentUserProvider; 14 | use Illuminate\Cache\CacheManager; 15 | use Illuminate\Contracts\Auth\Authenticatable; 16 | use Illuminate\Contracts\Auth\UserProvider; 17 | use Lcobucci\JWT\ValidationData; 18 | use MiladRahimi\LaraJwt\Exceptions\LaraJwtConfiguringException; 19 | use Illuminate\Config\Repository as Config; 20 | 21 | class JwtAuth implements JwtAuthInterface 22 | { 23 | /** 24 | * @var Closure[] 25 | */ 26 | private $filters = []; 27 | 28 | /** 29 | * @var string 30 | */ 31 | private $key; 32 | 33 | /** 34 | * @var int 35 | */ 36 | private $ttl; 37 | 38 | /** 39 | * @var string 40 | */ 41 | private $issuer; 42 | 43 | /** 44 | * @var string 45 | */ 46 | private $audience; 47 | 48 | /** 49 | * @var bool 50 | */ 51 | private $isModelSafe; 52 | 53 | /** 54 | * @var CacheManager 55 | */ 56 | private $cache; 57 | 58 | /** 59 | * @var Config 60 | */ 61 | private $config; 62 | 63 | /** 64 | * @var JwtServiceInterface 65 | */ 66 | private $service; 67 | 68 | /** 69 | * JwtAuth constructor. 70 | * 71 | * @throws LaraJwtConfiguringException 72 | */ 73 | public function __construct() 74 | { 75 | $this->cache = app('cache'); 76 | $this->config = app('config'); 77 | $this->service = app(JwtServiceInterface::class); 78 | $this->configure(); 79 | } 80 | 81 | /** 82 | * Check if configuration file is set up or not 83 | * 84 | * @throws LaraJwtConfiguringException 85 | */ 86 | private function configure() 87 | { 88 | if (empty($this->config->get('jwt')) || empty($this->config->get('jwt.key'))) { 89 | throw new LaraJwtConfiguringException('LaraJwt config not found.'); 90 | } 91 | 92 | $this->key = $this->config->get('jwt.key'); 93 | $this->ttl = $this->config->get('jwt.ttl', 60 * 60 * 24 * 30); 94 | $this->issuer = $this->config->get('jwt.issuer', 'Issuer'); 95 | $this->audience = $this->config->get('jwt.audience', 'Audience'); 96 | $this->isModelSafe = $this->config->get('jwt.model_safe', false); 97 | } 98 | 99 | /** 100 | * @inheritdoc 101 | */ 102 | public function generateToken(Authenticatable $user, array $customClaims = []): string 103 | { 104 | $tokenClaims = []; 105 | $tokenClaims['sub'] = $user->getAuthIdentifier();; 106 | $tokenClaims['iss'] = $this->issuer; 107 | $tokenClaims['aud'] = $this->audience; 108 | $tokenClaims['exp'] = time() + $this->ttl; 109 | $tokenClaims['iat'] = time(); 110 | $tokenClaims['nbf'] = time(); 111 | $tokenClaims['jti'] = uniqid(); 112 | 113 | foreach ($customClaims as $name => $value) { 114 | $tokenClaims[$name] = $value; 115 | } 116 | 117 | if ($this->isModelSafe) { 118 | $tokenClaims['model'] = get_class($user); 119 | } 120 | 121 | return $this->service->generate($tokenClaims, $this->key); 122 | } 123 | 124 | /** 125 | * @inheritdoc 126 | */ 127 | public function retrieveUser(string $jwt, UserProvider $provider = null) 128 | { 129 | $claims = $this->retrieveClaims($jwt); 130 | 131 | if (empty($claims)) { 132 | return null; 133 | } 134 | 135 | if (is_null($provider)) { 136 | $provider = app(EloquentUserProvider::class); 137 | } 138 | 139 | $key = $this->getUserCacheKey($claims['sub']); 140 | $ttl = $this->ttl / 60; 141 | 142 | return $this->cache->remember($key, $ttl, function () use ($claims, $provider) { 143 | $user = $provider->retrieveById($claims['sub']); 144 | 145 | if ($user == null) { 146 | return null; 147 | } 148 | 149 | if ($this->isModelSafe) { 150 | if (empty($claims['model']) || get_class($user) != $claims['model']) { 151 | return null; 152 | } 153 | } 154 | 155 | return $this->applyFilters($user); 156 | }); 157 | } 158 | 159 | /** 160 | * @inheritdoc 161 | */ 162 | public function retrieveClaims(string $jwt): array 163 | { 164 | if ($this->isJwtValid($jwt) == false) { 165 | return []; 166 | } 167 | 168 | return $this->service->parse($jwt, $this->key); 169 | } 170 | 171 | /** 172 | * @inheritdoc 173 | */ 174 | public function isJwtValid(string $jwt): bool 175 | { 176 | try { 177 | $validator = new ValidationData(); 178 | $validator->setIssuer($this->issuer); 179 | $validator->setAudience($this->audience); 180 | 181 | $claims = $this->service->parse($jwt, $this->key, $validator); 182 | 183 | if (isset($claims['sub'], $claims['jti'], $claims['exp']) == false) { 184 | return false; 185 | } 186 | 187 | if ($this->isTokenInvalidated($claims['jti'])) { 188 | return false; 189 | } 190 | 191 | return true; 192 | } catch (Exception $e) { 193 | return false; 194 | } 195 | } 196 | 197 | /** 198 | * @inheritdoc 199 | */ 200 | public function registerFilter(Closure $hook) 201 | { 202 | $this->filters[] = $hook; 203 | } 204 | 205 | /** 206 | * @inheritdoc 207 | */ 208 | private function applyFilters(Authenticatable $user) 209 | { 210 | if (empty($this->filters)) { 211 | return $user; 212 | } 213 | 214 | foreach ($this->filters as $hook) { 215 | $user = $hook($user); 216 | 217 | if ($user == null) { 218 | return null; 219 | } 220 | } 221 | 222 | return $user; 223 | } 224 | 225 | /** 226 | * @inheritdoc 227 | */ 228 | public function clearCache($user) 229 | { 230 | if ($user instanceof Authenticatable) { 231 | $user = $user->getAuthIdentifier(); 232 | } 233 | 234 | $this->cache->forget($this->getUserCacheKey($user)); 235 | } 236 | 237 | /** 238 | * @param $user 239 | * @return string 240 | */ 241 | private function getUserCacheKey($user) 242 | { 243 | if ($user instanceof Authenticatable) { 244 | $user = $user->getAuthIdentifier(); 245 | } 246 | 247 | return 'jwt:users:' . $user; 248 | } 249 | 250 | /** 251 | * @inheritdoc 252 | */ 253 | public function invalidate(string $jti) 254 | { 255 | $this->cache->put($this->getTokenInvalidationCacheKey($jti), time(), $this->ttl / 60); 256 | } 257 | 258 | /** 259 | * @param string $jti 260 | * @return string 261 | */ 262 | private function getTokenInvalidationCacheKey(string $jti) 263 | { 264 | return "jwt:invalidated:$jti"; 265 | } 266 | 267 | /** 268 | * Check if token is invalidated 269 | * 270 | * @param string $jti 271 | * @return bool 272 | */ 273 | private function isTokenInvalidated(string $jti): bool 274 | { 275 | return $this->cache->get($this->getTokenInvalidationCacheKey($jti)) ?: false; 276 | } 277 | } -------------------------------------------------------------------------------- /src/MiladRahimi/LaraJwt/Services/JwtAuthInterface.php: -------------------------------------------------------------------------------- 1 | 5 | * Date: 11/2/2017 AD 6 | * Time: 19:58 7 | */ 8 | 9 | namespace MiladRahimi\LaraJwt\Services; 10 | 11 | use Closure; 12 | use Illuminate\Contracts\Auth\Authenticatable; 13 | use Illuminate\Contracts\Auth\UserProvider; 14 | use MiladRahimi\LaraJwt\Exceptions\InvalidJwtException; 15 | 16 | interface JwtAuthInterface 17 | { 18 | /** 19 | * Generate JWT from authenticable model and custom claims 20 | * 21 | * @param Authenticatable $user 22 | * @param array $customClaims 23 | * @return string 24 | */ 25 | public function generateToken(Authenticatable $user, array $customClaims = []): string; 26 | 27 | /** 28 | * Retrieve user from given jwt via appropriate given user provider 29 | * 30 | * @param string $jwt 31 | * @param UserProvider $provider 32 | * @return Authenticatable|null 33 | */ 34 | public function retrieveUser(string $jwt, UserProvider $provider = null); 35 | 36 | /** 37 | * Retrieve claims from given jwt 38 | * (This method does not support filters and advanced validations) 39 | * 40 | * @param string $jwt 41 | * @return array 42 | */ 43 | public function retrieveClaims(string $jwt): array; 44 | 45 | /** 46 | * Is given JWT valid? 47 | * 48 | * @param string $jwt 49 | * @return bool 50 | */ 51 | public function isJwtValid(string $jwt): bool; 52 | 53 | /** 54 | * Register new filter 55 | * 56 | * @param Closure $hook 57 | */ 58 | public function registerFilter(Closure $hook); 59 | 60 | /** 61 | * Clear JWT cache 62 | * 63 | * @param Authenticatable|int $user 64 | */ 65 | public function clearCache($user); 66 | 67 | /** 68 | * Invalidate jwt by its jti 69 | * 70 | * @param string $jti 71 | */ 72 | public function invalidate(string $jti); 73 | } -------------------------------------------------------------------------------- /src/MiladRahimi/LaraJwt/Services/JwtService.php: -------------------------------------------------------------------------------- 1 | 5 | * Date: 9/18/17 6 | * Time: 15:46 7 | */ 8 | 9 | namespace MiladRahimi\LaraJwt\Services; 10 | 11 | use Exception; 12 | use Lcobucci\JWT\Builder as JwtBuilder; 13 | use Lcobucci\JWT\Claim\EqualsTo; 14 | use Lcobucci\JWT\Parser; 15 | use Lcobucci\JWT\Signer\BaseSigner; 16 | use Lcobucci\JWT\Token; 17 | use Lcobucci\JWT\ValidationData; 18 | use MiladRahimi\LaraJwt\Exceptions\InvalidJwtException; 19 | 20 | class JwtService implements JwtServiceInterface 21 | { 22 | /** 23 | * @var JwtBuilder 24 | */ 25 | private $builder; 26 | 27 | /** 28 | * @var Parser 29 | */ 30 | private $parser; 31 | 32 | /** 33 | * @var BaseSigner 34 | */ 35 | private $signer; 36 | 37 | /** 38 | * JwtService constructor. 39 | */ 40 | public function __construct() 41 | { 42 | $this->builder = app(JwtBuilder::class); 43 | $this->parser = app(Parser::class); 44 | $this->signer = app('larajwt.signer'); 45 | } 46 | 47 | /** 48 | * @inheritdoc 49 | */ 50 | public function generate(array $claims = [], string $key): string 51 | { 52 | $this->builder->unsign(); 53 | 54 | foreach ($claims as $name => $value) { 55 | $this->builder->set($name, $value); 56 | } 57 | 58 | return $this->builder->sign($this->signer, $key)->getToken(); 59 | } 60 | 61 | /** 62 | * @inheritdoc 63 | */ 64 | public function parse(string $jwt, string $key, ValidationData $validationData = null): array 65 | { 66 | try { 67 | /** @var Token $data */ 68 | $data = $this->parser->parse($jwt); 69 | } catch (Exception $e) { 70 | throw new InvalidJwtException($e->getMessage(), 0, $e); 71 | } 72 | 73 | if ($validationData && $data->validate($validationData) == false) { 74 | throw new InvalidJwtException('Jwt validation failed.'); 75 | } 76 | 77 | if ($data->verify(app('larajwt.signer'), $key) == false) { 78 | throw new InvalidJwtException('Jwt verification failed.'); 79 | } 80 | 81 | $claims = []; 82 | 83 | /** @var EqualsTo $claim */ 84 | foreach ($data->getClaims() as $claim) { 85 | $claims[$claim->getName()] = $claim->getValue(); 86 | } 87 | 88 | return $claims; 89 | } 90 | } -------------------------------------------------------------------------------- /src/MiladRahimi/LaraJwt/Services/JwtServiceInterface.php: -------------------------------------------------------------------------------- 1 | 5 | * Date: 11/2/2017 AD 6 | * Time: 12:38 7 | */ 8 | 9 | namespace MiladRahimi\LaraJwt\Services; 10 | 11 | use Lcobucci\JWT\ValidationData; 12 | use MiladRahimi\LaraJwt\Exceptions\InvalidJwtException; 13 | 14 | interface JwtServiceInterface 15 | { 16 | /** 17 | * Generate jwt from the given array of claims 18 | * 19 | * @param array $claims 20 | * @param string $key 21 | * 22 | * @return string 23 | */ 24 | public function generate(array $claims, string $key): string; 25 | 26 | /** 27 | * Parse (and validate) jwt to extract claims 28 | * 29 | * @param string $jwt 30 | * @param string $key 31 | * @param ValidationData|null $validationData 32 | * 33 | * @return string[] 34 | */ 35 | public function parse(string $jwt, string $key, ValidationData $validationData = null): array; 36 | } -------------------------------------------------------------------------------- /tests/Classes/Person.php: -------------------------------------------------------------------------------- 1 | 5 | * Date: 3/18/2018 AD 6 | * Time: 13:16 7 | */ 8 | 9 | namespace MiladRahimi\LaraJwtTests\Classes; 10 | 11 | use Illuminate\Auth\Authenticatable; 12 | use Illuminate\Database\Eloquent\Model; 13 | 14 | class Person extends Model implements \Illuminate\Contracts\Auth\Authenticatable 15 | { 16 | use Authenticatable; 17 | } -------------------------------------------------------------------------------- /tests/Classes/SomeException.php: -------------------------------------------------------------------------------- 1 | 5 | * Date: 3/18/2018 AD 6 | * Time: 14:23 7 | */ 8 | 9 | namespace MiladRahimi\LaraJwtTests\Classes; 10 | 11 | class SomeException extends \Exception 12 | { 13 | // Nada 14 | } -------------------------------------------------------------------------------- /tests/JwtAuthTest.php: -------------------------------------------------------------------------------- 1 | 8 | * Date: 11/2/2017 AD 9 | * Time: 10:59 10 | */ 11 | 12 | use Illuminate\Contracts\Auth\Authenticatable; 13 | use Illuminate\Foundation\Auth\User; 14 | use MiladRahimi\LaraJwt\Services\JwtAuth; 15 | use MiladRahimi\LaraJwt\Services\JwtAuthInterface; 16 | use MiladRahimi\LaraJwt\Services\JwtServiceInterface; 17 | use MiladRahimi\LaraJwtTests\Classes\Person; 18 | use MiladRahimi\LaraJwtTests\Classes\SomeException; 19 | 20 | class JwtAuthTest extends LaraJwtTestCase 21 | { 22 | public function test_generate_token_method_it_should_return_a_token() 23 | { 24 | $user = $this->generateUser(); 25 | 26 | /** @var JwtAuthInterface $jwtAuth */ 27 | $jwtAuth = $this->app[JwtAuthInterface::class]; 28 | 29 | $jwt = $jwtAuth->generateToken($user); 30 | 31 | $this->assertNotNull($jwt); 32 | 33 | return ['jwt' => $jwt, 'user' => $user]; 34 | } 35 | 36 | private function generateUserAndJwt(): array 37 | { 38 | $user = $this->generateUser(); 39 | 40 | /** @var JwtAuthInterface $jwtAuth */ 41 | $jwtAuth = $this->app[JwtAuthInterface::class]; 42 | 43 | $jwt = $jwtAuth->generateToken($user); 44 | 45 | return [$user, $jwt]; 46 | } 47 | 48 | 49 | public function test_retrieve_user_method_it_should_return_the_user_model() 50 | { 51 | list($user, $jwt) = $this->generateUserAndJwt(); 52 | 53 | $this->mockUserProvider($user); 54 | 55 | /** @var JwtAuthInterface $jwtAuth */ 56 | $jwtAuth = $this->app[JwtAuthInterface::class]; 57 | 58 | $parsedUser = $jwtAuth->retrieveUser($jwt); 59 | 60 | $this->assertEquals($user->getAuthIdentifier(), $parsedUser->getAuthIdentifier()); 61 | } 62 | 63 | public function test_retrieve_user_method_it_should_not_return_user_when_jwt_is_invalid() 64 | { 65 | list($user, $jwt) = $this->generateUserAndJwt(); 66 | 67 | $this->mockUserProvider($user); 68 | 69 | /** @var JwtAuthInterface $jwtAuth */ 70 | $jwtAuth = $this->app[JwtAuthInterface::class]; 71 | 72 | $parsedUser = $jwtAuth->retrieveUser($jwt . 'Invalidator'); 73 | 74 | $this->assertNull($parsedUser); 75 | } 76 | 77 | public function test_retrieve_user_method_it_should_not_return_user_when_model_is_not_valid_on_model_safe_mode() 78 | { 79 | $this->app['config']->set('jwt.model_safe', true); 80 | 81 | $person = new Person(); 82 | $person->setAttribute($person->getAuthIdentifierName(), 666); 83 | 84 | $user = app(User::class); 85 | $user->setAttribute($user->getAuthIdentifierName(), 666); 86 | 87 | $this->mockUserProvider($user); 88 | 89 | /** @var JwtAuthInterface $jwtAuth */ 90 | $jwtAuth = $this->app[JwtAuthInterface::class]; 91 | 92 | $jwt = $jwtAuth->generateToken($person); 93 | $parsedUser = $jwtAuth->retrieveUser($jwt); 94 | 95 | $this->assertNull($parsedUser); 96 | } 97 | 98 | public function test_retrieve_user_method_it_should_return_user_when_model_is_not_valid_out_of_model_safe_mode() 99 | { 100 | $this->app['config']->set('jwt.model_safe', false); 101 | 102 | $person = new Person(); 103 | $person->setAttribute($person->getAuthIdentifierName(), 666); 104 | 105 | $user = app(User::class); 106 | $user->setAttribute($user->getAuthIdentifierName(), 666); 107 | 108 | $this->mockUserProvider($user); 109 | 110 | /** @var JwtAuthInterface $jwtAuth */ 111 | $jwtAuth = $this->app[JwtAuthInterface::class]; 112 | 113 | $jwt = $jwtAuth->generateToken($person); 114 | $parsedUser = $jwtAuth->retrieveUser($jwt); 115 | 116 | $this->assertEquals($user->getAuthIdentifier(), $parsedUser->getAuthIdentifier()); 117 | } 118 | 119 | public function test_retrieve_user_method_it_should_not_return_user_when_jwt_is_expired() 120 | { 121 | $this->app['config']->set('jwt.ttl', -100); 122 | 123 | list($user, $jwt) = $this->generateUserAndJwt(); 124 | 125 | $this->mockUserProvider($user); 126 | 127 | /** @var JwtAuthInterface $jwtAuth */ 128 | $jwtAuth = $this->app[JwtAuthInterface::class]; 129 | 130 | $parsedUser = $jwtAuth->retrieveUser($jwt); 131 | 132 | $this->assertNull($parsedUser); 133 | } 134 | 135 | /** 136 | * @throws \MiladRahimi\LaraJwt\Exceptions\LaraJwtConfiguringException 137 | */ 138 | public function test_retrieve_user_method_it_should_not_return_user_when_issuer_is_not_the_same() 139 | { 140 | list($user, $jwt) = $this->generateUserAndJwt(); 141 | 142 | $this->mockUserProvider($user); 143 | 144 | $this->app['config']->set('jwt.issuer', 'Some thing new!'); 145 | 146 | $jwtAuth = new JwtAuth(); 147 | 148 | $parsedUser = $jwtAuth->retrieveUser($jwt); 149 | 150 | $this->assertNull($parsedUser); 151 | } 152 | 153 | /** 154 | * @throws \MiladRahimi\LaraJwt\Exceptions\LaraJwtConfiguringException 155 | */ 156 | public function test_retrieve_user_method_it_should_not_return_user_when_audience_is_not_the_same() 157 | { 158 | list($user, $jwt) = $this->generateUserAndJwt(); 159 | 160 | $this->mockUserProvider($user); 161 | 162 | $this->app['config']->set('jwt.audience', 'Some thing new!'); 163 | 164 | $jwtAuth = new JwtAuth(); 165 | 166 | $parsedUser = $jwtAuth->retrieveUser($jwt); 167 | 168 | $this->assertNull($parsedUser); 169 | } 170 | 171 | public function test_retrieve_user_method_it_should_not_return_user_when_his_jwt_is_invalidated() 172 | { 173 | list($user, $jwt) = $this->generateUserAndJwt(); 174 | 175 | $this->mockUserProvider($user); 176 | 177 | /** @var JwtAuthInterface $jwtAuth */ 178 | $jwtAuth = $this->app[JwtAuthInterface::class]; 179 | 180 | $claims = $jwtAuth->retrieveClaims($jwt); 181 | $jwtAuth->invalidate($claims['jti']); 182 | $parsedUser = $jwtAuth->retrieveUser($jwt); 183 | 184 | $this->assertNull($parsedUser); 185 | } 186 | 187 | public function test_retrieve_claims_method_it_should_retrieve_claims_from_jwt() 188 | { 189 | /** @var User $user */ 190 | list($user, $jwt) = $this->generateUserAndJwt(); 191 | 192 | /** @var JwtAuthInterface $jwtAuth */ 193 | $jwtAuth = $this->app[JwtAuthInterface::class]; 194 | 195 | $claims = $jwtAuth->retrieveClaims($jwt); 196 | 197 | $this->assertEquals($user->getAuthIdentifier(), $claims['sub']); 198 | $this->assertEquals($this->app['config']->get('jwt.issuer'), $claims['iss']); 199 | $this->assertEquals($this->app['config']->get('jwt.audience'), $claims['aud']); 200 | } 201 | 202 | public function test_is_jwt_valid_method_it_should_recognize_jwt_is_valid() 203 | { 204 | $jwt = $this->generateUserAndJwt()[1]; 205 | 206 | /** @var JwtAuthInterface $jwtAuth */ 207 | $jwtAuth = $this->app[JwtAuthInterface::class]; 208 | 209 | $this->assertEquals(true, $jwtAuth->isJwtValid($jwt)); 210 | } 211 | 212 | public function test_is_jwt_valid_method_it_should_say_the_jwt_is_invalid_when_it_is_not_valid() 213 | { 214 | $jwt = 'Shit'; 215 | 216 | /** @var JwtAuthInterface $jwtAuth */ 217 | $jwtAuth = $this->app[JwtAuthInterface::class]; 218 | 219 | $this->assertEquals(false, $jwtAuth->isJwtValid($jwt)); 220 | } 221 | 222 | public function test_is_jwt_valid_method_it_should_say_the_jwt_is_invalid_when_it_is_corrupted() 223 | { 224 | /** @var JwtServiceInterface $jwtService */ 225 | $jwtService = $this->app[JwtServiceInterface::class]; 226 | 227 | $jwt = $jwtService->generate(['sub' => 666], $this->key()); 228 | $jwt = substr($jwt, 0, strpos($jwt, '.')); 229 | 230 | /** @var JwtAuthInterface $jwtAuth */ 231 | $jwtAuth = $this->app[JwtAuthInterface::class]; 232 | 233 | $this->assertEquals(false, $jwtAuth->isJwtValid($jwt)); 234 | } 235 | 236 | public function test_is_jwt_valid_method_it_should_say_the_jwt_is_invalid_when_it_has_not_sub_claim() 237 | { 238 | /** @var JwtServiceInterface $jwtService */ 239 | $jwtService = $this->app[JwtServiceInterface::class]; 240 | 241 | $jwt = $jwtService->generate([], $this->key()); 242 | 243 | /** @var JwtAuthInterface $jwtAuth */ 244 | $jwtAuth = $this->app[JwtAuthInterface::class]; 245 | 246 | $this->assertEquals(false, $jwtAuth->isJwtValid($jwt)); 247 | } 248 | 249 | public function test_filters_it_should_when_there_are_some_registered_filters() 250 | { 251 | list($user, $jwt) = $this->generateUserAndJwt(); 252 | 253 | $this->mockUserProvider($user); 254 | 255 | /** @var JwtAuthInterface $jwtAuth */ 256 | $jwtAuth = $this->app[JwtAuthInterface::class]; 257 | 258 | $jwtAuth->registerFilter(function (Authenticatable $u) { 259 | $u->setRememberToken('some_token'); 260 | return $u; 261 | }); 262 | 263 | $user = $jwtAuth->retrieveUser($jwt); 264 | 265 | $this->assertEquals('some_token', $user->getRememberToken()); 266 | } 267 | 268 | /** 269 | * @test 270 | * @expectedException \MiladRahimi\LaraJwtTests\Classes\SomeException 271 | */ 272 | public function test_filters_it_should_throw_exception_when_there_is_a_filter_that_throws_an_exception() 273 | { 274 | list($user, $jwt) = $this->generateUserAndJwt(); 275 | 276 | $this->mockUserProvider($user); 277 | 278 | /** @var JwtAuthInterface $jwtAuth */ 279 | $jwtAuth = $this->app[JwtAuthInterface::class]; 280 | 281 | $jwtAuth->registerFilter(function (Authenticatable $u) { 282 | throw new SomeException($u); 283 | }); 284 | 285 | $jwtAuth->retrieveUser($jwt); 286 | } 287 | 288 | /** 289 | * @test 290 | * @throws \Illuminate\Container\EntryNotFoundException 291 | */ 292 | public function test_invalidate_token_it_should_invalidate_token() 293 | { 294 | $jwt = $this->generateUserAndJwt()[1]; 295 | 296 | /** @var JwtAuthInterface $jwtAuth */ 297 | $jwtAuth = $this->app[JwtAuthInterface::class]; 298 | 299 | $jti = $jwtAuth->retrieveClaims($jwt)['jti']; 300 | 301 | $jwtAuth->invalidate($jti); 302 | 303 | $time = time(); 304 | 305 | $cached = app('cache')->get("jwt:invalidated:$jti"); 306 | 307 | $this->assertLessThanOrEqual($time, $cached); 308 | 309 | $this->assertGreaterThanOrEqual(time(), $cached); 310 | } 311 | } -------------------------------------------------------------------------------- /tests/JwtGuardTest.php: -------------------------------------------------------------------------------- 1 | 16 | * Date: 12/6/2017 AD 17 | * Time: 10:59 18 | */ 19 | class JwtGuardTest extends LaraJwtTestCase 20 | { 21 | /** @var Jwt $guard */ 22 | private $guard; 23 | 24 | /** @var Authenticatable $user */ 25 | private $user; 26 | 27 | /** @var string $token */ 28 | private $token; 29 | 30 | public function setUp() 31 | { 32 | parent::setUp(); 33 | 34 | $this->user = $this->generateUser(); 35 | 36 | $this->guard = $this->createJwtGuard(); 37 | } 38 | 39 | private function createJwtGuard(array $claims = []): Jwt 40 | { 41 | $this->mockUserProvider($this->user); 42 | 43 | $this->token = app(JwtAuthInterface::class)->generateToken($this->user, $claims); 44 | $jwt = 'Bearer ' . $this->token; 45 | 46 | $request = Mockery::mock(Request::class)->makePartial(); 47 | $request->shouldReceive('header') 48 | ->withArgs(['Authorization']) 49 | ->andReturn($jwt) 50 | ->getMock(); 51 | 52 | return new Jwt($this->app[EloquentUserProvider::class], $request); 53 | } 54 | 55 | private function createVirginGuard() 56 | { 57 | $this->mockUserProvider($this->user); 58 | 59 | $request = Mockery::mock(Request::class)->makePartial(); 60 | $request->shouldReceive('header') 61 | ->withArgs(['Authorization']) 62 | ->andReturn('') 63 | ->getMock(); 64 | 65 | return new Jwt($this->app[EloquentUserProvider::class], $request); 66 | } 67 | 68 | public function test_get_token_method_it_should_return_the_token() 69 | { 70 | $this->assertEquals($this->token, $this->guard->getToken()); 71 | } 72 | 73 | public function test_get_token_method_it_should_return_null_when_there_is_no_user() 74 | { 75 | $this->assertNull($this->createVirginGuard()->getToken()); 76 | } 77 | 78 | public function test_login_and_user_and_get_user_methods_it_should_set_user() 79 | { 80 | $person = new Person(); 81 | $guard = $this->createVirginGuard(); 82 | $guard->login($person); 83 | 84 | $this->assertSame($guard->getUser(), $person); 85 | $this->assertSame($guard->user(), $person); 86 | } 87 | 88 | public function test_user_method_it_should_return_the_user() 89 | { 90 | $this->assertTrue($this->guard->user() instanceof Authenticatable); 91 | } 92 | 93 | public function test_guest_method_is_should_return_false_when_user_is_available() 94 | { 95 | $this->assertFalse($this->guard->guest()); 96 | } 97 | 98 | public function test_id_method_it_should_return_the_user_id() 99 | { 100 | $this->assertEquals($this->user->getAuthIdentifier(), $this->guard->id()); 101 | } 102 | 103 | public function test_logout_it_should_unset_user_from_guard() 104 | { 105 | $guard = $this->createJwtGuard(); 106 | $guard->logout(false); 107 | 108 | $this->assertNull($guard->user()); 109 | $this->assertNull($guard->getUser()); 110 | $this->assertNull($guard->getToken()); 111 | } 112 | 113 | public function test_logout_it_should_unset_user_from_guard_and_invalidate_jwt() 114 | { 115 | /** @var JwtAuthInterface $auth */ 116 | $auth = $this->app[JwtAuthInterface::class]; 117 | 118 | $guard = $this->createJwtGuard(); 119 | $jwt = $guard->getToken(); 120 | 121 | $this->assertNotNull($guard->user(), $auth->retrieveUser($jwt, $guard->getProvider())); 122 | 123 | $guard->logout(true); 124 | 125 | $this->assertNull($guard->user()); 126 | $this->assertNull($auth->retrieveUser($jwt, $guard->getProvider())); 127 | } 128 | 129 | public function test_get_claims_it_should_return_empty_array_when_user_is_not_set() 130 | { 131 | $guard = $this->createVirginGuard(); 132 | $this->assertEmpty($guard->getClaims()); 133 | } 134 | 135 | public function test_get_claims_it_should_return_claim_array_when_user_is_set() 136 | { 137 | $claims = $this->createJwtGuard()->getClaims(); 138 | $this->assertNotEmpty($claims); 139 | } 140 | 141 | public function test_get_claim_method_it_should_return_null_when_user_is_not_set() 142 | { 143 | $guard = $this->createVirginGuard(); 144 | $this->assertNull($guard->getClaim('sub')); 145 | } 146 | 147 | public function test_get_claim_method_it_should_return_null_when_claim_is_not_in_token() 148 | { 149 | $guard = $this->createJwtGuard(); 150 | $this->assertNull($guard->getClaim('sth')); 151 | } 152 | 153 | public function test_get_claim_method_it_should_return_claim() 154 | { 155 | $guard = $this->createJwtGuard(); 156 | $this->assertEquals($guard->user()->getAuthIdentifier(), $guard->getClaim('sub')); 157 | } 158 | } -------------------------------------------------------------------------------- /tests/JwtServiceTest.php: -------------------------------------------------------------------------------- 1 | 8 | * Date: 9/18/17 9 | * Time: 16:00 10 | */ 11 | 12 | use Lcobucci\JWT\ValidationData; 13 | use MiladRahimi\LaraJwt\Services\JwtServiceInterface; 14 | 15 | class JwtServiceTest extends LaraJwtTestCase 16 | { 17 | /** 18 | * @test 19 | */ 20 | public function it_should_generate_a_token_and_parse_it() 21 | { 22 | $key = $this->key(); 23 | $claims = $this->generateClaims(); 24 | 25 | $jwtService = app(JwtServiceInterface::class); 26 | $jwt = $jwtService->generate($claims, $key); 27 | $parsedClaims = $jwtService->parse($jwt, $key, new ValidationData()); 28 | 29 | $this->assertEquals($claims['iss'], $parsedClaims['iss']); 30 | $this->assertEquals($claims['sub'], $parsedClaims['sub']); 31 | $this->assertEquals($claims['aud'], $parsedClaims['aud']); 32 | $this->assertEquals($claims['nbf'], $parsedClaims['nbf']); 33 | $this->assertEquals($claims['iat'], $parsedClaims['iat']); 34 | $this->assertEquals($claims['exp'], $parsedClaims['exp']); 35 | $this->assertEquals($claims['jti'], $parsedClaims['jti']); 36 | } 37 | 38 | /** 39 | * Generate testing claims 40 | * 41 | * @return array 42 | */ 43 | private function generateClaims(): array 44 | { 45 | $claims = []; 46 | $claims['iss'] = 'Issuer'; 47 | $claims['sub'] = 'Subject'; 48 | $claims['aud'] = 'The Audience'; 49 | $claims['nbf'] = (string)time(); 50 | $claims['iat'] = (string)time(); 51 | $claims['exp'] = (string)(time() + 60 * 60 * 24); 52 | $claims['jti'] = (string)mt_rand(1, 999); 53 | 54 | return $claims; 55 | } 56 | 57 | /** 58 | * @test 59 | * @expectedException \MiladRahimi\LaraJwt\Exceptions\InvalidJwtException 60 | */ 61 | public function it_should_raise_an_error_when_token_is_expired() 62 | { 63 | $key = $this->key(); 64 | $claims = $this->generateClaims(); 65 | 66 | $claims['exp'] = time() - 1; 67 | 68 | $jwtService = app(JwtServiceInterface::class); 69 | $jwt = $jwtService->generate($claims, $key); 70 | 71 | $jwtService->parse($jwt, $key, app(ValidationData::class)); 72 | } 73 | 74 | /** 75 | * @test 76 | * @expectedException \MiladRahimi\LaraJwt\Exceptions\InvalidJwtException 77 | */ 78 | public function it_should_raise_an_error_when_token_is_not_valid() 79 | { 80 | $key = $this->key(); 81 | 82 | $jwt = 'Invalid Token'; 83 | 84 | $jwtService = app(JwtServiceInterface::class); 85 | $jwtService->parse($jwt, $key); 86 | } 87 | } -------------------------------------------------------------------------------- /tests/LaraJwtTestCase.php: -------------------------------------------------------------------------------- 1 | 17 | * Date: 9/20/17 18 | * Time: 12:55 19 | */ 20 | class LaraJwtTestCase extends TestCase 21 | { 22 | /** 23 | * @var \Faker\Generator $faker 24 | */ 25 | protected $faker; 26 | 27 | /** 28 | * @inheritdoc 29 | */ 30 | public function setUp() 31 | { 32 | parent::setUp(); 33 | 34 | $_ENV['APP_ENV'] = 'testing'; 35 | 36 | $this->faker = FakerFactory::create(); 37 | } 38 | 39 | /** 40 | * @inheritdoc 41 | */ 42 | protected function getPackageProviders($app) 43 | { 44 | return [ServiceProvider::class]; 45 | } 46 | 47 | /** 48 | * @inheritdoc 49 | */ 50 | protected function getEnvironmentSetUp($app) 51 | { 52 | // Config 53 | $app['config']->set('jwt.key', $this->key()); 54 | $app['config']->set('jwt.ttl', 60 * 60 * 24 * 30); 55 | $app['config']->set('jwt.issuer', 'The Issuer'); 56 | $app['config']->set('jwt.audience', 'The Audience'); 57 | $app['config']->set('jwt.model_safe', false); 58 | } 59 | 60 | /** 61 | * Generate JWT Key (Singleton) 62 | * 63 | * @return string 64 | */ 65 | protected function key(): string 66 | { 67 | return $_ENV['JWT_KEY'] ?? $_ENV['JWT_KEY'] = Str::random(32); 68 | } 69 | 70 | /** 71 | * Generate a brand new user 72 | * 73 | * @return User 74 | */ 75 | protected function generateUser(): User 76 | { 77 | $id = $this->faker->numberBetween(1, 1000); 78 | 79 | $user = app(User::class); 80 | 81 | $idFieldName = $user->getAuthIdentifierName(); 82 | $user->setAttribute($idFieldName, $id); 83 | 84 | return $user; 85 | } 86 | 87 | /** 88 | * Mock User Provider service 89 | * 90 | * @param Authenticatable $user 91 | * @return Authenticatable 92 | */ 93 | protected function mockUserProvider(Authenticatable $user): Authenticatable 94 | { 95 | $userProviderMock = Mockery::mock(EloquentUserProvider::class) 96 | ->shouldReceive('retrieveById')->withArgs([$user->getAuthIdentifier()]) 97 | ->andReturn($user) 98 | ->getMock(); 99 | 100 | $this->app[EloquentUserProvider::class] = $userProviderMock; 101 | 102 | return $user; 103 | } 104 | } --------------------------------------------------------------------------------