Sunday , January 16 2022

Laravel REST API Authentication using Passport – Android Coding by DMTechnolab

Do you want to know about a proper token based authentication mechanism for your RESTful API? If yes, then you are at right place. In this post we will know Laravel REST API Authentication using Passport.

We’ve built the RESTful API many times before, but we’ve never discussed the proper Automation. And that’s why I am writing this post.

In this post, we will create a RESTful API using login and signup Laravel. So now, without wasting much time, let’s start.

Laravel REST API Authentication using Passport-Video

If you’re more comfortable watching video tutorials than reading long posts, don’t worry; I also have a step video step playlist for this topic.

He said that the government has taken several steps to prevent such incidents.He said that the government has taken several steps to prevent such incidents.He said that the government has taken several steps to prevent such incidents.He said that the government has taken several steps to prevent such incidents.He said that the government has taken several steps to prevent such incidents.

But if you are okay with reading the post, then let’s move on.

Setting everything

We must prepare our development environment before we start. So here are the things that I will use.

  • XAMPP (You can use other tools like mamp, wamp as well).
  • Creator (Get it by clicking on the link)
  • NodeJS
  • Visual Studio Code (or basically any code editor program).

Once you have all the above things, you are good to go.

Build a larval project

Now, you select a location in the machine where you want to save your project. Open a terminal or command prompt here.

  • To create the larva project we will run the following command.
composer create-project laravel/laravel MyAPIProject

  • In the above order MyAPIProject Our project is named. You can change it if you want.

Application launch

  • Our vacant project is ready and now we can launch it locally.
  • Go inside your project directory and execute the following command.
php artisan serve

Laravel Project Services

  • If you go to the address shown in your browser, you will see your Larva home page.

Database setting

Once you have created the project, it is necessary that you setup a database for your application.

  • Go to phpMyAdmin (localhost / phpmyadmin) and create a database.
  • Now open the .env file which is inside your project folder and make the following changes.
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:u7kC40c8iedM7PcSLWc0ggvxs1Iy+UmEpVseyMtu4BY=
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=mywebapp
DB_USERNAME=root
DB_PASSWORD=
DB_SOCKET=/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock

  • You need to define values DB_DATABASE, DB_USER_NAME, DB_PASSWORD And if you are using a Linux based system then you have to define a new value DB_SOCKET As you can see above.

Create authentication

Authenticating with Laravel is extremely easy, everything is already done and we just need to execute some commands.

  • First we need the UI package of larvae.
composer require laravel/ui

  • Then we will create ort with this command.
php artisan ui vue --auth

  • After running the above command, you will see login and register button in your home page.

Laravel Authentic

  • However, we need some more commands to do everything.
  • First we will install all the required node packages.
npm install

  • After installing all the required node packages, run the following command.
npm run dev

  • And finally we will migrate the database using the following command.
php artisan migrate

  • Now our authentication is done and we can signup and login to our app.

Add a Laravel Passport

  • Now the first larval passport is required which we will use for our API.
composer require laravel/passport

  • Migrate again using database
php artisan migrate

  • Now we need to generate the required key for the passport.
php artisan passport:install

Configure passport

  • Open your User Model class and add the following lines.
use LaravelPassportHasApiTokens;

class User extends Authenticatable
{
    use Notifiable, HasApiTokens;
    .
    .

  • Now we need to call Passport :: Routes () in our App Providers AuthServiceProvider.php class.
<?php

namespace AppProviders;

use IlluminateFoundationSupportProvidersAuthServiceProvider as ServiceProvider;
use IlluminateSupportFacadesGate;
use LaravelPassportPassport;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        // 'AppModel' => 'AppPoliciesModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();
        Passport::routes();
        //
    }
}

  • Come in now Config / phew File and here we will define passport as the driver of our apis.
'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
            'hash' => false,
        ],
    ],

Now passport configuration is done, and we can create our API routes. But first we will create an AuthController.

Creating an authentic controller

  • First run the following command.
php artisan make:controller AuthController

  • Now go inside AuthController.php which is generated and write the following code.
<?php

namespace AppHttpControllersApi;

use AppHttpControllersController;
use IlluminateHttpRequest;
use AppUser;
use IlluminateSupportFacadesAuth;

class AuthController extends Controller
{
    
    public function login(Request $request){
        
        $request->validate([
            'email' => 'required|string',
            'password' => 'required|string'
        ]);

        $credentials = request(['email', 'password']);

        if(!Auth::attempt($credentials)){
            return response()->json([
                'message'=> 'Invalid email or password'
            ], 401);
        }

        $user = $request->user();

        $token = $user->createToken('Access Token');

        $user->access_token = $token->accessToken;

        return response()->json([
            "user"=>$user
        ], 200);
    }

    public function signup(Request $request){

        $request->validate([
            'name' => 'required|string',
            'email' => 'required|string|email|unique:users',
            'password' => 'required|string|confirmed'
        ]);
        
        $user = new User([
            'name'=>$request->name,
            'email'=>$request->email,
            'password'=>bcrypt($request->password)
        ]);

        $user->save();

        return response()->json([
            "message" => "User registered successfully"
        ], 201);
        
    }

    public function logout(Request $request){
        $request->user()->token()->revoke(); 
        return response()->json([
            "message"=>"User logged out successfully"
        ], 200);
    }

    public function index(){
        echo "Hello World";
    }

}

  • Now we create our API route. Then open Routes / api.php And write the following code.
<?php

use IlluminateHttpRequest;
use IlluminateSupportFacadesRoute;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::namespace('Api')->group(function(){

    Route::prefix('auth')->group(function(){

        Route::post('login', 'AuthController@login');
        Route::post('signup', 'AuthController@signup');

    });

    Route::group([
        'middleware'=>'auth:api'
    ], function(){
        
        
        Route::get('helloworld', 'AuthController@index');
        Route::post('logout', 'AuthController@logout');

    });

});

  • and you are. You can test your API using POSTMAN or any other REST client.

Project deployment for server

Now if you want to deploy your project on live server then it is also very easy. Watch this video on how to do it.

If you need a detailed explanation then you should check all the video tutorials.

Larvel REST API Authentication Source Code

Finally, if you need my source code, you can get it from here.

All this tutorial is for friends. If you have any problem or confusion about this Larvel REST API Authentication So feel free to comment below. Thank you


Source link

About dmtechnolab

Check Also

Simplified Coding

Android Espresso Tutorial – Testing Fragment in Isolation – Android Coding by DMTechnolab

Welcome to another tutorial in the Android test series. And this post is called Android …

One comment

  1. Wow, that’s very educative.

Leave a Reply

Your email address will not be published. Required fields are marked *