facebook

Restful API In Laravel 5.5 Using Jwt Authentication in Ubuntu

By Santanu Aich

Laravel

Restful API In Laravel 5.5 Using Jwt Authentication in Ubuntu

Rest is a stateless client-server protocol, where each HTTP requests contains all the information to run it. So, there is no need to remember the previous state, which makes the API become stateless. Using API, we can easily create web services that connect with our codebase/database and getting data either in XML or JSON format as a response.

 

Now, we integrate Jwt Authentication in Laravel(5.5) for creating secure restful API.

> Open your terminal > Creating a new project in Laravel by below command

composer create-project –prefer-dist laravel/laravel jwt_rest

Now we use the JWT package in our newly installed Laravel.

Use the below code in your terminal, but the Laravel version should be 5.5 or above.

composer require tymon/jwt-auth:dev-develop --prefer-source

As a result, a new file jwt.php is created inside the config folder.

 

‘secret’ => env(‘JWT_SECRET’),

/*

|————————————————————————–

| JWT Authentication Keys

|————————————————————————–

|

| The algorithm you are using, will determine whether your tokens are

| signed with a random string (defined in `JWT_SECRET`) or using the

| following public & private keys.

|

| Symmetric Algorithms:

| HS256, HS384 & HS512 will use `JWT_SECRET`.

|

| Asymmetric Algorithms:

| RS256, RS384 & RS512 / ES256, ES384 & ES512 will use the keys below.

|

*/

‘keys’ => [

/*

|————————————————————————–

| Public Key

|————————————————————————–

|

| A path or resource to your public key.

|

| E.g. ‘file://path/to/public/key’

|

*/

‘public’ => env(‘JWT_PUBLIC_KEY’),

/*

|————————————————————————–

| Private Key

|————————————————————————–

|

| A path or resource to your private key.

|

| E.g. ‘file://path/to/private/key’

|

*/

‘private’ => env(‘JWT_PRIVATE_KEY’),

 

 

 

Please check the above code in jwt.php, which need some key. These keys will be signed with an encryption key.

To generate the secret key, please run the below code

php artisan jwt:secret

Now registering auth.jwt middleware inside app/Http/kernel.php

protected $middleware = [

..

..

‘auth.jwt’ => \Tymon\JWTAuth\Http\Middleware\Authenticate::class,

];

Set Routes: open the api.php from routes folder and set up all the routes for your project.

Update app/User.php as below

 

 

<?phpnamespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
use Notifiable;

/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
‘name’, ’email’, ‘password’,
];

/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
‘password’, ‘remember_token’,
];

/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* @return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}

/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* @return array
*/
public function getJWTCustomClaims()
{
return [];
}
}

 

User registration requires name, email, and password. So, create a form request for validating the data. Please use the following command:

php artisan make:request RegisterAuthRequest

Please go to the app/Http, a new folder Request is created, a new file RegisterAuthRequest.php is created, open it and replace the rules method in below

 

public function rules()

    {

        return [

            'name' =>
'required|string',

            'email' =>
'required|email|unique:users',

            'password' =>
'required|string|min:6|max:10'

        ];

    }

Create a new ApiController by running the command:

php artisan make:controller ApiController

A new controller  ApiController.php will be created which consist of 4 functions.

They are register(), login(), logout(), getAuthUser().

register():  a successful response is returned with the user data that you have given on the registration form.

login(): JWTAuth::attempt() is used for login action. A token is created for a successful login.

logout(): If you click on logout, the token is expired successfully.

getAuthUser(): if the user is validated, you get a token and can be identified as a current user.

Santanu Aich Author
Senior Software Engineer , Openweb Solutions

Senior Software Engineer at Openweb Solutions

Posts created 6

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top
shares