Home > database >  how to check santcum middleware in middleware class in laravel
how to check santcum middleware in middleware class in laravel

Time:04-27

i have two type of api authentication way and i want if my first way fails check santcum laravel auth . i make midlleware class and but i dont know how to check santcum in that

<?php

namespace App\Http\Middleware;



class UserApiAuthenticated
{

/**
 * User authenticator container
 * @var UserAuthenticatorServiceInterface
 */
protected UserAuthenticatorServiceInterface $user_authenticator_service;

public function __construct(UserAuthenticatorServiceInterface$user_authenticator_service)
{
    $this->user_authenticator_service = $user_authenticator_service;
}

/**
 * Handle an incoming request.
 *
 * @param \Illuminate\Http\Request $request
 * @param \Closure(\Illuminate\Http\Request): 
 (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
 * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
 */
public function handle(Request $request, Closure $next)
{
    if ($this->user_authenticator_service->isUserAuthenticated($request)) {
        return $next($request);
    } elseif () {


}

CodePudding user response:

I would do something like that :

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @param string|null              ...$guards
     *
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next, ...$guards)
    {
        $guards = empty($guards) ? [null] : $guards;

        foreach ($guards as $guard)
        {
            if (Auth::guard($guard)->check())
            {
                return $next($request);
            }
        }


        abort(403, 'Unauthenticated')
    }

it checks all the guards one by one, when you use the middleware you set the guards :

->middleware('mymiddleware:web,sanctum')

or with a route group :

Route::group(['middleware' => ['mymiddleware:web,sanctum', 

if you have routes in common, you could use both guards at the same time, and for routes that are specific to one authentication method, you can set the correct guard you need

but in the end i would check the auth middleware from laravel, i'm sure it does what you need (Illuminate\Auth\Middleware\Authenticate)

  • Related