Verify user when Laravel admin calls api, Laravel guard uses correct posture

What is a Guard?

Guard is an important part of the permission authentication component of the Laravel framework:

1. Your application may be divided into front-end users and back-end management users.

2. Your application may be both a traditional php rendered html application and an api interface service for other applications such as Android mobile applications.

These needs are taken into account by laravel!

In conf/auth.php, guards can configure users and use the call middleware mode

It solves the need for different clients to use different user roles (front-end users, back-end users) for authorization in different environments (api, web, admin)

[
    'guards' => [
        'web' => [ 
            //Indicates use web Use "under middleware" session Driver drive position: vendor\laravel\framework\src\Illuminate\Auth\SessionGuard.php
            //Users for Users -- Specifically define the users model as defined in the provider 
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            //Indicates use api Use "under middleware" token Driver" 
            //Users for Users -- Specifically define the users model as defined in the provider 
//Note that the api does not have a default Authenticate middleware configuration - --- you need to manually add it yourself in app/http/kernel.php
'driver' => 'token', 'provider' => 'users', 'hash' => false, ], 'admin' => [ //Indicates use admin Use "under middleware" session Driver" //Users for Users -- Specifically define the users model as defined in the provider 'driver' => 'session', 'provider' => 'admin', ], ] ]

  

By the way, the user's data provider simply defines the user type and specifies the corresponding user model

[
    'providers' => [
        //Express users User Use App\User::class Model as User Model
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
        //You can also configure other users, such as admin Background user
        'admin' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ],
    ]
]

 

Using the Guard method

Specify guard to get current session user information

Auth::guard('web')->user() 

Get current session login information using default guard

Auth::user();

Note: The default configuration is config/auth.php

'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
]

If this is the configuration above, auth::user() is equivalent to Auth::guard('web') ->user();

 

 

How do I use privilege authentication in routing?

1. First, understand how laravel middleware is used:

Middleware registers the following arrays in app\Http\Kernel.php by default (rules):

Middleware registered in the $middleware array All routes are invoked every time

protected $middleware = [
    \App\Http\Middleware\TrustProxies::class,
    \Fruitcake\Cors\HandleCors::class,
    \App\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];

The middleware registered in the $middlewareGroups array is a routing group, which is called every time an alias is called (packaged call)

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
         \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];
Registered in the $routeMiddleware array can be used alone or with middlewareGroups
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];

 

Routing uses the user authentication method (using the default auth middleware method)

//adopt auth Middleware uses" admin guard"Validate Middleware 
Route::middleware('auth:admin')->get('/', function () {
    return view('welcome');
});

Description: auth:admin

auth Middleware / where a colon represents a parameter, admin is the admin registered in guard as follows:

[
    'admin' => [
        //Indicates use admin Use "under middleware" session Driver" 
        //Users for Users -- Specifically define the users model as defined in the provider 
        'driver'   => 'session',
        'provider' => 'admin',
    ]
]

This auth:admin represents:

This route requires user authentication: authenticate whether it is an admin user or not, and depending on the configuration of the admin guard, the session module will be called to authenticate the user

 

Laravel Authenticate authentication process

laravel privilege authentication, all done in Authenticate middleware, default file is \App\Http\Middleware\Authenticate.php

Inject into middleware module via kernel (registered with App\HttpKernel.php)

It implements authentication through the guard module, which is registered in the config\auth.php mentioned above

 

The guard module is used in Authenticate to verify that the user is logged in:

The following code snippet is located at: Illuminate\AuthMiddleware\Authenticate

class Authenticate implements AuthenticatesRequests
{
    /**
     * The authentication factory instance.
     *
     * @var \Illuminate\Contracts\Auth\Factory
     */
    protected $auth;

    /**
     * Create a new middleware instance.
     *
     * @param  \Illuminate\Contracts\Auth\Factory  $auth
     * @return void
     */
    public function __construct(Auth $auth)
    {
        $this->auth = $auth;
    }
    //...
}

 

Permission auth entication is triggered when the routing component uses \App\Http\Middleware\Authenticate::class Middleware

Later, there will be middleware to complete the specific operations, such as jumping to the login page when you find that you are not logged in

 

 

 

 

Actual Warfare: Laravel-Admin calls the query interface and does not allow unregistered users to access the api

Modify the use of api Middleware in app/http/Kernel.php because the session driver used by default admin guard requires that token, session middleware support, be turned on

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,//Enable token middleware
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,//Enable session middleware
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
         \App\Http\Middleware\VerifyCsrfToken::class,//Verification csrf middleware
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        \App\Http\Middleware\EncryptCookies::class,//New Enables token
        \Illuminate\Session\Middleware\StartSession::class,//New Enables session middleware
        \App\Http\Middleware\VerifyCsrfToken::class,//New Enables csrf middleware
        'throttle:60,1',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];

 

Add the required route to the routing interface and add "admin.auth" to the middleware to indicate that it is ok ay to use admin privilege validation

Route::middleware('admin.auth')->get('/company', function (Request $request) {
    return Company::select(['id',"name as text"])->get();
});

 

 

These are all personal summaries, refer to the online tutorials and laravel related source code, if there are errors and understanding problems, welcome big guys to correct!

Original Link: https://www.cnblogs.com/zjhblogs/p/12525125.html

Tags: PHP Session Laravel Android

Posted on Thu, 19 Mar 2020 19:05:56 -0700 by ijmccoy