Skip to content

Commit b7bc613

Browse files
author
Diego Hernandes
committed
finishing up.
1 parent 173c2c0 commit b7bc613

File tree

6 files changed

+292
-37
lines changed

6 files changed

+292
-37
lines changed

config/jwt.php

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -80,21 +80,23 @@
8080
|
8181
*/
8282

83-
'refresh_limit' => 7200
83+
'refresh_limit' => 7200,
8484

8585
/*
86-
| That's it. there's nothing more to configure.
87-
|
88-
| Things like cache for blacklist and user model provider will be read from
89-
| your default configurations.
86+
|--------------------------------------------------------------------------
87+
| Auto Guard Binding By Middleware Match
88+
|--------------------------------------------------------------------------
9089
|
91-
| Blacklisted tokens will be stored within your cache driver for the following time:
90+
| Useful when your application has more than 1 guard, and the JWT powered one
91+
| is not the default.
9292
|
93-
| ttl + refresh_limit.
93+
| If your application is a API only, you can safely set this to false.
9494
|
95-
| After this time has been passed, the token cannot be refresh anyway so it will automatically
96-
| be purged from your cache.
95+
| Setting it to false without having JWT guard as default will make
96+
| mandatory using the suffix :guardName when using the 'auth' middleware.
9797
|
9898
*/
9999

100+
'middleware_match' => true,
101+
100102
];

readme.md

Lines changed: 246 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,246 @@
1+
# Laravel JWT
2+
3+
![Readme Art](http://imageshack.com/a/img923/9629/0S3fQu.png)
4+
5+
This package provides out-of-the-box API authentication using JWT for Laravel.
6+
7+
## Installation.
8+
9+
You can install this package by running:
10+
11+
```bash
12+
composer require kino/laravel-jwt
13+
```
14+
15+
## Setup.
16+
17+
In order to setup this package into your application, minimal configuration
18+
is actually needed.
19+
20+
#### 1) Service Provider.
21+
22+
Register this package's Service Provider by adding it to the `providers`
23+
section of your `config/app.php` file:
24+
25+
```php
26+
'providers' => [
27+
28+
// ... other providers omitted
29+
30+
Kino\Auth\JWT\ServiceProvider::class,
31+
32+
],
33+
```
34+
35+
#### 2) Configuration file.
36+
37+
Publish the configuration file (`config/jwt.php`) by running the
38+
following command after registering the Service Provider.
39+
40+
```bash
41+
php artisan vendor:publish --provider="Kino\Auth\JWT\ServiceProvider"
42+
```
43+
44+
#### 3) Generate a Secret.
45+
46+
In order for this package to works, you will need a separate secret
47+
(do not use the application key).
48+
49+
This package provides a command that can be used for generating a strong key.
50+
51+
Get a new key by running:
52+
53+
```bash
54+
php artisan jwt:generate
55+
```
56+
57+
Then, copy the generated key contents into your `.env` file.
58+
59+
**NOTICE**: The key generation process will not automatically
60+
set it inside your `.env` file, do it manually.
61+
62+
#### 4) Setup Guard
63+
64+
In order to automatically authenticate your routes using `JWT` tokens,
65+
you need to change the guard driver to `jwt`
66+
67+
Inside `config/auth.php` set the corresponding guard group you want to protect:
68+
69+
If you have the default guard group named `api`, your `auth.php`
70+
should be like this:
71+
72+
```php
73+
'guards' => [
74+
// ... other guards omitted.
75+
76+
'api' => [
77+
'driver' => 'jwt', // this is the line you need to change.
78+
'provider' => 'users',
79+
],
80+
],
81+
```
82+
83+
That's it, we are all ready to use it.
84+
85+
86+
87+
## Usage.
88+
89+
This package aims to be dead simple to use.
90+
91+
The following templates can be used to setup your existing
92+
authentication controllers and resources.
93+
94+
**NOTICE**: Full working examples of use for this package
95+
will be added on this package when it reaches it's 1.0 version.
96+
97+
### Protecting Routes.
98+
99+
This package is fully integrated with Laravel Authentication.
100+
101+
The default configuration (`config/jwt.php`) brings a sensitive value that
102+
is very useful when your application is not completely an API: **`'middleware_match`**
103+
104+
By not completely an API, I mean, the JWT guard is not the default one.
105+
106+
In those cases, in order to use the `auth` middleware, the config key
107+
**`middleware_match`** **MUST** be set to true.
108+
109+
This configuration key allows non protected routes to work properly.
110+
111+
Notice that this option will match middleware group names with guard names.
112+
113+
> In this case, the 'api' middleware group will always use the `api` guard.
114+
> Also, the 'web' middleware group will always use the `web` guard.
115+
116+
If you do not use this value, you will need to use suffixes when referencing the
117+
`auth` middleware, like `auth:api`.
118+
119+
120+
### Issuing and Renewing Tokens.
121+
122+
For issuing tokens, no special class is actually needed,
123+
you can just expect create a Guard current implementation from the IoC and work from there.
124+
125+
Check out the examples.
126+
127+
128+
** On the following examples, all Guard instances are injected from `Illuminate\Contracts\Auth\Guard` **
129+
** On the following examples, all Request instances are injected from `Illuminate\Http\Request` **
130+
131+
#### Token from User Instance.
132+
133+
This method should be used when you just registered a user and any other
134+
special cases.
135+
136+
```php
137+
138+
public function tokenFromUser(Guard $auth)
139+
{
140+
// generating a token from a given user.
141+
$user = SomeUserModel::find(12);
142+
143+
// logs in the user
144+
$auth->login($user);
145+
146+
// get and return a new token
147+
$token = $auth->issue();
148+
149+
return $token;
150+
}
151+
152+
```
153+
154+
#### Token from User Credentials.
155+
156+
This method should be used when you just registered a user and any other
157+
special cases.
158+
159+
```php
160+
161+
public function tokenFromCredentials(Guard $auth, Request $request)
162+
{
163+
// get some credentials
164+
$credentials = $request->only(['email', 'password']);
165+
166+
if ($auth->attempt($credentials)) {
167+
return $token = $auth->issue();
168+
}
169+
170+
return ['Invalid Credentials'];
171+
}
172+
173+
```
174+
175+
#### Refreshing Tokens.
176+
177+
Tokens can be refreshed in 2 different ways: Auto detect or manual.
178+
179+
If you do not pass any argument into the refresh method, the Guard will
180+
look for either a **`Authorization`** header or a **`token`** field on the
181+
request's body.
182+
183+
```php
184+
185+
public function refreshToken(Guard $auth)
186+
{
187+
// auto detecting token from request.
188+
$token = $auth->refresh();
189+
190+
// manually passing the token to be refreshed.
191+
$token = $auth->refresh($oldToken);
192+
193+
return $token;
194+
}
195+
```
196+
197+
### Custom Claims.
198+
199+
Of course, there are support for custom claims.
200+
201+
You can set them in two ways.
202+
203+
#### By explicitly passing them.
204+
205+
```php
206+
207+
$customClaims = [
208+
'custom1' => 'value1',
209+
'custom2' => 'value2',
210+
];
211+
212+
// when issuing
213+
$auth->issue($customClaims);
214+
215+
// when refreshing
216+
// custom claims are the second parameter as the first one is the
217+
// old token
218+
$auth->refresh(null, $customClaims);
219+
220+
```
221+
222+
#### By Authenticatable method.
223+
224+
If all your users will have the same custom claims, you can setup a default
225+
custom claims method on your User's model (or any other Authenticatable you're using):
226+
227+
If the method `customJWTClaims()` is present on the model being issue the token against,
228+
this claims will be automatically included.
229+
230+
```php
231+
232+
class User extends Model implements Authenticatable
233+
{
234+
public function customJWTClaims()
235+
{
236+
return [
237+
'email' => $this->email,
238+
'name' => $this->name,
239+
];
240+
}
241+
}
242+
243+
244+
245+
246+
```

src/Auth/Guard.php

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -398,13 +398,14 @@ public function issue(array $customClaims = [])
398398
/**
399399
* Refresh a given token.
400400
*
401-
* @param array $customClaims
401+
* @param string $token
402+
* @param array $customClaims
402403
* @return bool|string
403404
*/
404-
public function refresh(array $customClaims = [])
405+
public function refresh(string $token = null, array $customClaims = [])
405406
{
406-
// detects the request token.
407-
$token = $this->detectedToken();
407+
// detect token if none was passed.
408+
$token = $token ?? $this->detectedToken();
408409

409410
// if no token was detected.
410411
if (!$token) {
@@ -425,6 +426,9 @@ public function refresh(array $customClaims = [])
425426
return false;
426427
}
427428

429+
// set the user instance.
430+
$this->user = $user;
431+
428432
// try to issue a new token and refresh
429433
try {
430434
return $this->manager()->issue($user, $customClaims);

src/Auth/ServiceProvider.php

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44

55
use Illuminate\Contracts\Auth\UserProvider;
66
use Illuminate\Foundation\Support\Providers\AuthServiceProvider;
7-
use Illuminate\Support\Facades\Auth;
87
use Kino\Auth\JWT\Contracts\Token\Manager as TokenManager;
98
use Illuminate\Auth\AuthManager;
109

src/Contracts/Auth/Guard.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,10 +59,11 @@ public function manager();
5959
/**
6060
* Refresh a given token.
6161
*
62-
* @param array $customClaims
62+
* @param string $token
63+
* @param array $customClaims
6364
* @return bool|string
6465
*/
65-
public function refresh(array $customClaims = []);
66+
public function refresh(string $token = null, array $customClaims = []);
6667

6768
/**
6869
* Issue a token for the current authenticated user.

0 commit comments

Comments
 (0)