user633440
user633440

Reputation:

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?

Upvotes: 5

Views: 7169

Answers (4)

EeetM
EeetM

Reputation: 23

yes. you can create jwt token without database using tymondesigns/jwt-auth package...

for that you have to use jwt::encode method...

let me explain ...

first you have to put your credential in .env file... then i am recomending you to use custom claims ...

after that you can create jwt token using below code ...

$customClaims = ['foo' => 'bar', 'baz' => 'bob'];
$factory = JWTFactory::customClaims($customClaims);
$token = JWTAuth::encode($payload);

for further details you can refer below link

wiki

Upvotes: 1

user633440
user633440

Reputation:

As a quick fix I decided to implement the following custom code...

1) Created custom middleware to handle the logic.

class CustomMiddleware
{
    protected $loginPath = 'login';

    public function handle($request, Closure $next) {
        $logged_in = $request->session()->get('logged_in');

        if (!$logged_in) {
            return redirect()->guest('login')->with('flag','1');
        }

    return $next($request);
    }
}

2) Added a reference to the middleware class.

class Kernel extends HttpKernel
{
    protected $routeMiddleware = [
        'custom' => \App\Http\Middleware\CustomMiddleware::class,
    ];
}

3) Added it to routes.php.

Route::group(['middleware' => ['custom']], function () {
    // Add routes here
}

Upvotes: 0

whoan
whoan

Reputation: 8521

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.

Upvotes: 4

Davor Minchorov
Davor Minchorov

Reputation: 2076

JWTAuth::attempt() won't help you with this, because it hits the database for you behind the scenes. You need some other way to check the environment credentials.

Add a custom method to a class somewhere which will do that for you or pass the credentials against the API you are hitting with Guzzle.

Code example:

public function authenticate($username, $password)
{
    if(!$username === env('USERNAME') or !$password === env('PASSWORD')) {
       // return a message that the user could not be authenticated or false.
    }


    // Generate the JWT token here and store it somewhere. 
}

Upvotes: 1

Related Questions