Skip to content

Commit a29455c

Browse files
authored
Merge pull request #3 from andrewdyer/2.x
2.x
2 parents 7ec369b + 28cb552 commit a29455c

28 files changed

+1537
-3183
lines changed

.php_cs

Lines changed: 0 additions & 26 deletions
This file was deleted.

README.md

Lines changed: 105 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -1,121 +1,161 @@
1-
<h1 align="center">JWT Auth</h1>
1+
# JWT-Auth
22

3-
<p align="center">A simple framework-agnostic JSON Web Token authentication solution.</p>
3+
A simple framework-agnostic JSON Web Token authentication solution.
44

5-
<p align="center">
6-
<a href="https://packagist.org/packages/andrewdyer/jwt-auth"><img src="https://poser.pugx.org/andrewdyer/jwt-auth/downloads?style=for-the-badge" alt="Total Downloads"></a>
7-
<a href="https://packagist.org/packages/andrewdyer/jwt-auth"><img src="https://poser.pugx.org/andrewdyer/jwt-auth/v?style=for-the-badge" alt="Latest Stable Version"></a>
8-
<a href="https://packagist.org/packages/andrewdyer/jwt-auth"><img src="https://poser.pugx.org/andrewdyer/jwt-auth/license?style=for-the-badge" alt="License"></a>
9-
</p>
10-
11-
## License
12-
Licensed under MIT. Totally free for private or commercial projects.
5+
[![Latest Stable Version](http://poser.pugx.org/andrewdyer/jwt-auth/v?style=for-the-badge)](https://packagist.org/packages/andrewdyer/jwt-auth) [![Total Downloads](http://poser.pugx.org/andrewdyer/jwt-auth/downloads?style=for-the-badge)](https://packagist.org/packages/andrewdyer/jwt-auth) [![Latest Unstable Version](http://poser.pugx.org/andrewdyer/jwt-auth/v/unstable?style=for-the-badge)](https://packagist.org/packages/andrewdyer/jwt-auth) [![License](http://poser.pugx.org/andrewdyer/jwt-auth/license?style=for-the-badge)](https://packagist.org/packages/andrewdyer/jwt-auth) [![PHP Version Require](http://poser.pugx.org/andrewdyer/jwt-auth/require/php?style=for-the-badge)](https://packagist.org/packages/andrewdyer/jwt-auth)
136

147
## Installation
15-
```text
8+
9+
```bash
1610
composer require andrewdyer/jwt-auth
1711
```
1812

19-
## Usage
13+
## Getting Started
14+
15+
### Define the JWT Subject
16+
17+
Create a class (e.g., `User`) that implements the `JWTSubject` interface. This class must provide a method `getJWTIdentifier` to return the user’s unique identifier.
18+
2019
```php
21-
// Create a new auth provider instance
22-
$authProvider = new App\Providers\AuthProvider();
23-
24-
// Create a new jwt provider instance
25-
$jwtProvider = new App\Providers\JwtProvider();
26-
27-
// Build up jwt claims
28-
$claimsFactory = new Anddye\JwtAuth\ClaimsFactory::build([
29-
'exp' => 1582243200, // Friday, 21 February 2020 00:00:00
30-
'iat' => 1582193571, // Thursday, 20 February 2020 10:12:51
31-
'iss' => 'https://example.com',
32-
'jti' => 'fVcx9BJHqh',
33-
'nbj' => '1582193571', // Thursday, 20 February 2020 10:12:51
34-
]);
20+
namespace App\Models;
3521

36-
// Bring everything together to create a jwt auth instance
37-
$jwtAuth = new JwtAuth($authProvider, $jwtProvider, $claimsFactory);
22+
use Anddye\JWTAuth\Interfaces\JWTSubject;
23+
24+
class User implements JWTSubject
25+
{
26+
public function getJWTIdentifier(): int
27+
{
28+
return 1;
29+
}
30+
}
3831
```
3932

40-
### Auth Provider
33+
> **Note:** This example is simplified for demonstration purposes. In a real-world application, you would typically use a proper user model, such as one provided by your framework. Ensure the `getJWTIdentifier` method returns a unique user identifier appropriate for your system.
34+
35+
### Create an Authentication Provider
36+
37+
Create an authentication provider class that implements `AuthProviderInterface`. This class will handle credential validation and user retrieval by ID.
38+
4139
```php
4240
namespace App\Providers;
4341

44-
use Anddye\JwtAuth\Providers\AuthProviderInterface;
42+
use Anddye\JWTAuth\Interfaces\AuthProviderInterface;
43+
use App\Models\User;
4544

4645
class AuthProvider implements AuthProviderInterface
4746
{
4847
public function byCredentials(string $username, string $password)
4948
{
50-
// TODO: Validate username / password and return an instance of `Anddye\JwtAuth\Contracts\JwtSubject`
49+
if ($username === 'admin' && $password === 'secret') {
50+
return new User();
51+
}
52+
53+
return null;
5154
}
5255

5356
public function byId(int $id)
5457
{
55-
// TODO: Find a user by id and return an instance of `Anddye\JwtAuth\Contracts\JwtSubject` if exists
58+
if ($id === 1) {
59+
return new User();
60+
}
61+
62+
return null;
5663
}
5764
}
5865
```
5966

60-
### JWT Provider
67+
> **Note:** This example uses hardcoded credentials for demonstration purposes. In a real-world application, you should validate credentials securely by checking against a database and using hashed passwords (e.g., via libraries like `bcrypt` or `password_hash`). Ensure you follow best practices for secure authentication.
68+
69+
### Create a JWT Provider
70+
71+
Create a JWT provider class that implements `JWTProviderInterface`. This class should handle encoding and decoding JWT tokens.
72+
6173
```php
62-
namespace Anddye\JwtAuth\Tests\Stubs\Providers;
74+
namespace App\Providers;
6375

64-
use Anddye\JwtAuth\Providers\JwtProviderInterface;
76+
use Anddye\JWTAuth\Interfaces\JWTProviderInterface;
6577

66-
class JwtProvider implements JwtProviderInterface
78+
class JWTProvider implements JWTProviderInterface
6779
{
6880
public function decode(string $token)
6981
{
70-
// TODO: Decode JWT token somehow
82+
return json_decode(base64_decode($token), true);
7183
}
7284

7385
public function encode(array $claims): string
7486
{
75-
// TODO: Encode claims and create a JWT token somehow
87+
return base64_encode(json_encode($claims));
7688
}
7789
}
7890
```
7991

80-
### Claims Factory
81-
| Option | Type | Description |
82-
| --- | --- | --- |
83-
| exp | int | Time after which the JWT expires. |
84-
| iat | int | Time at which the JWT was issued. |
85-
| iss | string | Issuer of the JWT. |
86-
| jti | string | Unique identifier; can be used to prevent the JWT from being replayed. |
87-
| nbj | int | Time before which the JWT must not be accepted for processing. |
92+
> **Note:** This examples used `base64_encode` and `base64_decode` for simplicity. For real-world usage, consider using a proper JWT library such as [firebase/php-jwt](https://github.com/firebase/php-jwt) for better security.
93+
94+
### Generate JWT Claims
95+
96+
The `ClaimsFactory` class helps create a JWT claims instance. The `build` method accepts an array of claims and returns an instance of `ClaimsInterface`.
8897

8998
```php
90-
$claimsFactory = new Anddye\JwtAuth\ClaimsFactory();
91-
$claimsFactory->setExp(1582243200); // Friday, 21 February 2020 00:00:00
92-
$claimsFactory->setIat(1582193571); // Thursday, 20 February 2020 10:12:51
93-
$claimsFactory->setIss('https://example.com');
94-
$claimsFactory->setJti('fVcx9BJHqh');
95-
$claimsFactory->setNbj(1582193571); // Thursday, 20 February 2020 10:12:51
99+
use Anddye\JWTAuth\Factory\ClaimsFactory;
100+
101+
$claims = ClaimsFactory::build([
102+
'iss' => 'https://example.com', // Issuer of the JWT
103+
'aud' => 'https://example.com', // Audience of the JWT
104+
'exp' => 1582243200, // Expiration time (Unix timestamp)
105+
'nbf' => 1582193571, // Not before time (Unix timestamp)
106+
'iat' => 1582193571, // Issued at time (Unix timestamp)
107+
'jti' => 'fVcx9BJHqh', // Unique identifier
108+
]);
96109
```
97110

98-
### Attempt with credentials
111+
> **Note:** This example uses hardcoded Unix timestamps for demonstration purposes. Consider using libraries like [nesbot/carbon](https://github.com/briannesbitt/carbon) or PHP's native `DateTime` class to generate timestamps dynamically. This helps improve readability and ensures accurate date handling.
112+
113+
### Initialize the JWT Authenticator
114+
115+
Create a new instance of the `JWTAuth` class. This requires an instance of `AuthProviderInterface`, `JWTProviderInterface`, and `ClaimsInterface`.
116+
99117
```php
100-
if (!$token = $jwtAuth->attempt($username, $password)) {
101-
// TODO: Handle failed attempt with credentials
118+
use App\Providers\AuthProvider;
119+
use App\Providers\JWTProvider;
120+
use Anddye\JWTAuth\JWTAuth;
121+
122+
$authProvider = new AuthProvider();
123+
124+
$jwtProvider = new JWTProvider();
125+
126+
$jwtAuth = new JWTAuth($authProvider, $jwtProvider, $claims);
127+
```
128+
129+
## Usage
130+
131+
### Attempt Authentication
132+
133+
Authenticate a user by providing their credentials. If successful, a JWT token will be returned.
134+
135+
```php
136+
$token = $jwtAuth->attempt('admin', 'secret');
137+
138+
if ($token) {
139+
echo "Token: " . $token;
102140
} else {
103-
// TODO: Handle successful attempt with credentials
141+
echo "Invalid credentials";
104142
}
105143
```
106144

107-
### Authenticate with token
145+
### Authenticate a Token
146+
147+
Validate a JWT token and retrieve the associated user (subject).
148+
108149
```php
109-
if (!$actor = $jwtAuth->authenticate($token)->getActor()) {
110-
// TODO: Handle failed authentication with token
150+
$subject = $jwtAuth->authenticate('your-jwt-token-here');
151+
152+
if ($subject) {
153+
echo "User authenticated!";
111154
} else {
112-
// TODO: Handle successful authentication with token
155+
echo "Invalid token";
113156
}
114157
```
115158

116-
## Support
117-
If you're using this package, I'd love to hear your thoughts! Feel free to contact me on [Twitter](https://twitter.com/andyer92).
118-
119-
Need to see an example? Check out [this tutorial](https://github.com/andrewdyer/jwt-auth/wiki/Slim-3-Example) on how to integrate this library into a [Slim 3](http://www.slimframework.com/docs/v3/) project.
159+
## License
120160

121-
Found a bug? Please report it using the [issue tracker](https://github.com/andrewdyer/jwt-auth/issues), or better yet, fork the repository and submit a pull request.
161+
Licensed under MIT. Totally free for private or commercial projects.

composer.json

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,23 +18,21 @@
1818
],
1919
"autoload": {
2020
"psr-4": {
21-
"Anddye\\JwtAuth\\": "src"
21+
"Anddye\\JWTAuth\\": "src"
2222
}
2323
},
2424
"autoload-dev": {
2525
"psr-4": {
26-
"Anddye\\JwtAuth\\Tests\\": "tests"
26+
"Anddye\\JWTAuth\\Tests\\": "tests"
2727
}
2828
},
2929
"require": {
30-
"php": "^7.2.5"
30+
"php": "^8.2"
3131
},
3232
"require-dev": {
33-
"phpunit/phpunit": "^8.5",
34-
"friendsofphp/php-cs-fixer": "^2.16",
35-
"symfony/var-dumper": "^5.0",
36-
"nesbot/carbon": "^2.30",
37-
"firebase/php-jwt": "^5.0 || ^6.0"
33+
"phpunit/phpunit": "^11.5",
34+
"symfony/var-dumper": "^7.2",
35+
"firebase/php-jwt": "^6.10"
3836
},
3937
"scripts": {
4038
"cs": [

0 commit comments

Comments
 (0)