Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set up JWT-Auth with Laravel 5

Pretty new to laravel and I'm creating backend API for Angularjs application with it, and now I'm stuck at the authentication part.

I decided to go for https://github.com/tymondesigns/jwt-auth to handle the authentication and tokens.

Problem is, the wiki of JWT-Auth doesn't tell me anything about how to setup user database. It only tells me that I can autheticate like this

    $token = JWTAuth::attempt($credentials)

But of course it won't work before it has some place to look up for those credentials.

How do I manage to do this?

Thanks!

like image 905
jyDev Avatar asked Sep 28 '22 10:09

jyDev


1 Answers

Laravel 5 comes with User model already, if you have migrated the User table to your database (set database credentials in the .env file in your project root) using php artisan migrate, then it's a simple matter of creating a user.

The migration files for the User model should already be included too.

Then you can create a user by making a database seed, or simply execute:

User::create(
     [
         'name' => 'you', 
         'email' => '[email protected]', 
         'password' => Hash::make('secret')
     ]
);

You can then login using JWTAuth with the credentials in an array like

['email' => '[email protected]', 'password' => 'secret']

Depending on where you call the User::create(), you might have to include

use App\User;

in the top of your Controller, where App is your app's namepace. App is the default namespace, but you can easily change this to whatever you want , it is entirely optional and you don't have to do this. Just adding this, in case you changed it.

Edit: Perhaps this external tutorial on scotch.io might help you more in the long run.

like image 166
Francesco de Guytenaere Avatar answered Sep 30 '22 00:09

Francesco de Guytenaere