Nette IUserStorage implementation using JWT access token instead of PHP sessions.
Disclaimer: If you don't know what JWT is, please refer to JWT draft or to JWT homepage.
On user login, the application stores jwt_access_token
cookie instead of bad old PHPSESSID
one.
The cookie contains an encoded JWT signed by the application. The user authentication is then based
on verifying the JWT rather than the session.
Warning: CSRF protection rules still apply!
This means you no longer need to solve PHP session implementation, scaling and testing problems.
All the things that you would normally store in the SessionStorage
can be stored in a key-value
storage, where the JWT is a key.
This also means your application is ready to become SPA in the future. :)
Register the extension in your config.neon
.
extensions:
jwtUserStorage: Marten\Nette\JwtStorage\DI\JWTUserStorageExtension
Then configure its required properties.
JWTUserStorage:
privateKey: 'secret-cat' # this secret is used to sign the JWT
algorithm: 'HS256' # this is the signing algorithm
Both the JWT and the cookie in which it's stored is by default set to expire in 20 days. If you want to fiddle
with expiration time, use expiration
option:
JWTUserStorage:
expiration: 20 days # sets JWT and cookie expiration time to 20 days (this is the default option)
expiration: 20 minutes # sets JWT and cookie expiration time to 20 minutes
expiration: false # sets JWT and cookie to never expire
By default, jti
and iat
(see JWT draft) are added
to your JWTs. If you don't want to use them, set generateJti
and generateIat
options to false.
JWTUserStorage:
generateJti: false # disables jti generation for your JWT access tokens
generateIat: false # disables iat generation for your JWT access tokens
If you want to define your own Nette\Security\IIdentity
serializer, which serializes your identity implementation
into the JWT body, you can implement Marten\Nette\JwtStorage\\IIdentitySerializer
namespace Your\Own;
class IdentitySerializer implements \Marten\Nette\JwtStorage\Security\IIdentitySerializer
{
// ...
}
and register it in configuration.
JWTUserStorage:
identitySerializer: Your\Own\IdentitySerializer
And that's it, you're ready to go!
- If you are developing an app with JWT User Storage and you still see
PHPSESSID
in your cookies, it's probably because Tracy\Tracy uses it.
- Czech discussion thread on Nette Forum