Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JWT authentication in Laravel without database

I have a question regarding Authentication in Laravel 5.x. I’ve been specifically looking at tymondesigns/jwt-auth and irazasyed/jwt-auth-guard packages to do the JSON web token authentication token handling in my Laravel application.

I am not using a local database whatsoever, nor do I want to. I have environment variables set up in .env for my API’s URL, USERNAME & PASSWORD. The Guzzle PHP HTTP client is doing the trick just fine, connecting and returning data between the API and my application as needed.

However, I need to set up Authentication within my Laravel instance. I run into problems here, and the auth is wanting a DB connection.

$token = JWTAuth::attempt($credentials)

Here's the exception:

PDOException in Connector.php line 55: 
SQLSTATE[HY000] [14] unable to open database file
  1. How can I make use of JWT without using a database?
  2. How can I COMPLETELY shut-off database connections within Laravel?

Thanks.


UPDATE:

Using tymon/jwt-auth, I've set things up within the routes, Kernel, Middleware, etc.

I created a "claim" successfully, but I need to create the token by encoding the "payload."

$this->username = $request->username;

$sub = $this->username;
$iat = time();
$jti = md5($sub . $iat);
$aud = env('APP_URL');

$this->claims = [
    'sub' => $sub,
    'iat' => $iat,
    'exp' => time() + (2 * 7 * 24 * 60 * 60),
    'nbf' => $iat,
    'iss' => 'khill',
    'jti' => $jti,
    'aud' => $aud,
];

$payload = JWTFactory::make($this->claims);

How do I get the custom token?

like image 865
Karl Hill Avatar asked Jun 08 '16 13:06

Karl Hill


Video Answer


1 Answers

You should define a custom Authentication Provider and set it in config/jwt.php.


Example of provider

Put this class anywhere you like.

namespace MyNamespace;

use Tymon\JWTAuth\Providers\Auth\AuthInterface;

class MyCustomAuthenticationProvider implements AuthInterface
{
    public function byCredentials(array $credentials = [])
    {
        return $credentials['username'] == env('USERNAME') && $credentials['password'] == env('PASSWORD');
    }

    public function byId($id)
    {
        // maybe throw an expection?
    }

    public function user()
    {
        // you will have to implement this maybe.
    }
}

Example of configuration

In the providers array in config/jwt.php, change this:

'auth' => 'Tymon\JWTAuth\Providers\Auth\IlluminateAuthAdapter',

to this:

'auth' => 'MyNamespace\MyCustomAuthenticationProvider',

Other considerations

  1. Using the env() function anywhere is not good practice. It's better to use it in your config files, and then use the config() function anywhere else.

  2. You may need to reimplement also the User Provider.

like image 76
whoan Avatar answered Sep 21 '22 21:09

whoan