Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

javid020's avatar

Using Laravel 5.8 authentication with external JSON API (Creating own ServiceProvider)

Hi,

I'm building a Laravel 5.8 application to be the front-end to an external API written in Go. I POST a user/pass to the API which then responds with either HTTP/200 and a JSON Token (JWT) or an HTTP/401 to signal the credentials are invalid.

I would like to use Laravel's built-in auth mechanism (or anything which makes this work really) to be able to create pages and routes only for logged in users. It seems a lot of work to reinvent the wheel.

[TLDR] Basically I need some code which checks if the API returns an HTTP/200, stores the token somewhere (session/cookie [but not database]) and then provide's some way to easily (virtually) log users into the Laravel app. That way I can create pages for logged in users only.

So far I have done this:

APIUser class:


protected $attributes = [];

    public function __construct($attributes)
    {
        $this->attributes = $attributes;
    }
    public function __get($attribute)
    {
        return $this->attributes[$attribute];
    }
    public function getKey()
    {
        return $this->attributes['userId'];
    }
    /**
     * Get the name of the unique identifier for the user.
     *
     * @return string
     */
    public function getAuthIdentifierName()
    {
        return 'userId';
    }
    /**
     * Get the unique identifier for the user.
     *
     * @return mixed
     */
    public function getAuthIdentifier()
    {
        return $this->attributes['userId'];
    }
    /**
     * Get the password for the user.
     *
     * @return string
     */
    public function getAuthPassword()
    {
        return null;
    }

    public function getAuthIdentifierEmail()
    {
        return $this->attributes['email'];
    }

    /**
     * Get the token value for the "remember me" session.
     *
     * @return string
     */
    public function getRememberToken()
    {
        return $this->attributes[$this->getRememberTokenName()];
    }
    /**
     * Set the token value for the "remember me" session.
     *
     * @param  string  $value
     * @return void
     */
    public function setRememberToken($value)
    {
        $this->attributes[$this->getRememberTokenName()] = $value;
    }
    /**
     * Get the column name for the "remember me" token.
     *
     * @return string
     */
    public function getRememberTokenName()
    {
    }

    public function getAttributes()
    {
        return $this->attributes;
    }

ApiUserProvider:

protected $model;
    protected $modelUser;

    public function __construct(Request $request)
    {
        $this->model = APIUser::class;
    }

    public function fetchUser($credentials) {
        if ($credentials['email'] and $credentials['password']) {
            $email = $credentials['email'];
            $password = $credentials['password'];

            $client = new \GuzzleHttp\Client([
                'headers' => ['Content-Type' => 'application/json'],
            ]);

            $url = config('apilist.login');

            try {
                $response = $client->request('POST', $url, [
                    'json' => [
                        'email' => $email,
                        'password' => sha1($password),
                    ],
                ]);
            } catch (GuzzleException $e) {
                print_r($e->getResponse());
            }

            $array = json_decode($response->getBody()->getContents(), true);


            if($array["responseMessage"]["code"] == 200){

                $userInfo = $array["responseMessage"]["object"];

                return new $this->model($userInfo);

            } else {
                return $array["responseMessage"]["message"] ?: "Something went wrong. Please try again";
            }
        }
    }

    public function retrieveById($identifier) {
        return $this->modelUser;
    }

    /**
     * Retrieve a user by their unique identifier and "remember me" token.
     *
     * @param  mixed  $identifier
     * @param  string  $token
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByToken($identifier, $token) {}

    /**
     * Update the "remember me" token for the given user in storage.
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @param  string  $token
     * @return void
     */
    public function updateRememberToken(Authenticatable $user, $token){}

    /**
     * Retrieve a user by the given credentials.
     *
     * @param  array  $credentials
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByCredentials(array $credentials){
        $user = $this->fetchUser($credentials);

        return $user;
    }

    /**
     * Validate a user against the given credentials.
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @param  array  $credentials
     * @return bool
     */
    public function validateCredentials(Authenticatable $user, array $credentials){
        //return ($credentials['email'] == $user->getAuthIdentifierEmail());
        return true;
    }

config/auth.php:


'providers' => [
        'users' => [
            'driver' => 'apiuserprovider',
        ],

And in the login function, when I do

dd($this->guard()->user());

it gives me user's information. Everything works fine, however, it does not login a user to the system. What is the problem?

0 likes
5 replies
mvd's avatar

Hi @javid020

Did you call Auth::login($user);? Can you show us the login functionality?

javid020's avatar

@mvd

Here is my login:

$credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            // Authentication passed...
            return redirect()->intended('/');
        }

mvd's avatar

@javid020

What do you mean with not logged in? Is this another request after the login request?

javid020's avatar

In the beginning, in DebugBar it shows that web guard is null ( https://ibb.co/4NZkdyy ). When I click the "Login" button with credentials, in a moment it assigns user and its information to web guard ( https://ibb.co/zn1rbqH ) and then again sets it to null. For this reason, after login, I cannot use @guest method and also can again enter to the login page. How to prevent that?

mvd's avatar

@javid020 I am not sure but you login with ajax. Do you use the @guest function after refresh the page?

Please or to participate in this conversation.