jwt authentication code example
Example 1: what is jsonwebtoken
JSON Web Token is an Internet standard for creating data with optional
signature and/or optional encryption whose payload holds JSON that asserts
some number of claims.
The tokens are signed either using a private secret or a public/private key.
Example 2: vanilla javascript jwt authentication laravel
In my guest RedirectIfAuthenticated middleware check for cookie, if exists, setToken which in turn sets Guard to Authenticated and will always redirect to /home if token is available and valid:
public function handle($request, Closure $next, $guard = null)
{
if ($request->hasCookie('access_token')) {
Auth::setToken($request->cookie('access_token'));
}
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
return $next($request);
}
And In my post-auth Routes middleware I also setToken and if its valid and exists, will allow access, otherwise will throw a range of JWT errors which just redirect to pre-auth view:
public function handle($request, Closure $next)
{
JWTAuth::setToken($request->cookie('access_token'))->authenticate();
return $next($request);
}
Example 3: jsonwebtoken
RSASHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
,
)
Example 4: jsonwebtoken
jwt.sign({ exp: Math.floor(Date.now() / 1000) + (60 * 60), data: 'foobar'}, 'secret');