1

I'm using Laravel Sanctum 3.x in my Laravel 9 project. I'm building a Microservice feature and need to authenticate them via my Microservice model where I've added HasApiTokens and created my tokens.

I've created the extra auth config:

'guards' => [
    'api' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'microservice' => [
        'driver' => 'session',
        'provider' => 'microservices',
    ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],
    'microservices' => [
        'driver' => 'eloquent',
        'model' => App\Models\Microservice::class,
    ],

    // 'users' => [
    //     'driver' => 'database',
    //     'table' => 'users',
    // ],
],

Then, inside my controller where I'd like to use my microservice auth check rather than the default auth:sanctum middleware check I'm confused as to what to add?

This is my controller:

<?php

namespace App\Http\Controllers\Hub;

use App\Http\Controllers\Controller;
use App\Http\Responses\ApiSuccessResponse;
use App\Http\Responses\ApiErrorResponse;
use App\Http\Responses\ApiValidationErrorResponse;
use Illuminate\Http\Request;
use App\Models\Microservice;

class HubController extends Controller
{
    /**
     * Instantiate a new HubController instance.
     *
     * @return void
     */
    public function __construct()
    {
        // TODO: how to change to Microservice auth?
        $this->middleware('auth:sanctum');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function __invoke(Request $request)
    {
        return new ApiSuccessResponse(null, [
            'message' => 'Hub controller - post'
        ]);
    }
}

Would I just need to change the auth:sanctum to auth:microservice and then it would validate the token?

1 Answer 1

0

You need to pass guard to your authentication logic .

if(auth()->guard('microservices')->attempt($request->only('email','password'))) {
    return auth()->guard('admin')->user(); }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.