Home > Mobile >  Laravel passport return a short token and don't work
Laravel passport return a short token and don't work

Time:09-11

This is my implementation of passport for the latest version of Laravel, unfortunately that return a short token and when I want to test my apis it doesn't work and return my requests to login page

composer require laravel/passport
php artisan migrate
php artisan passport:install
php artisan passport:client --personal

composer.json

"laravel/framework": "^9.28",
"laravel/passport": "^11.1",
"laravel/sanctum": "^3.0",

simplified PASSPORT_PUBLIC_KEY and PASSPORT_PRIVATE_KEYkeys from .env

PASSPORT_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----
MIIJQgIBADANBgkqh ... 94sYgy2AiPQIQLmup/VEzr96YaYh JiWjAWUaOH0wAdOve8h
FDAeXetZhQ5OjXB85aL7VoOilhS3Og==
-----END PRIVATE KEY-----"

PASSPORT_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA5OgR4HT3UzoFyGLIkJu/
cpzF ... 25ECAwEAAQ==
-----END PUBLIC KEY-----"

routes:

Route::prefix('v1')->name('Api/v1')->group(function(){
    //login
    Route::post('login',[MyApiController::class,'login']);

    Route::middleware('auth:api')->group(function(){
        //mikrotik api's
        Route::post('add-user',[MyApiController::class,'add_user']);
    });
});

auth.php:

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

now when I try to create token by this below code:

$user = User::find(1);
$token = $user->createToken($user->email)->accessToken;

AuthServiceProvider

class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
        'App\Models\Model' => 'App\Policies\ModelPolicy',
    ];

    public function boot(): void
    {
        $this->registerPolicies();
        Passport::useTokenModel(Token::class);
        Passport::useClientModel(Client::class);
        Passport::useAuthCodeModel(AuthCode::class);
        Passport::usePersonalAccessClientModel(PersonalAccessClient::class);
    }
}

I get this short token:

{
    "email": "[email protected]",
    "job_title": "",
    "address": "",
    "category": "",
    "plan": "",
    "start": "",
    "end": "",
    "logo": "",
    "token": "8e788ab34c00a217e18c48414aed900a505798c60b4fe7e60684b9f79b223f64"
}

UPDATED

public function login(CustomerLoginRequest $_): JsonResponse
{
    $user = user();
    if ($user) {
        $attempt = auth()->attempt(
            [
                'mobile_number' => _g('mobile_number'),
                'password' => _g('password')
            ],
            false,
        );
        if ($attempt) {
            $token = $user->createToken($user->email)->accessToken;
            return $this->successFull(
                [
                    'username' => $user->username,
                    'name_family' => $user->name_family,
                    'phone' => $user->phone,
                    'mobile_number' => $user->mobile_number,
                    'email' => $user->email,
                    'job_title' => $user->job_title,
                    'address' => $user->address,
                    'category' => $user->category,
                    'plan' => $user->plan,
                    'start' => $user->start,
                    'end' => $user->end,
                    'logo' => $user->logo,
                    'token' => $token->token
                ]
            );
        } else {
            return $this->unAuthorized();
        }
    } else {
        return $this->notFound();
    }
}

User class:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

/**
 * @mixin IdeHelperUser
 */
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

CodePudding user response:

The issue here easily made and simple to resolve. Laravel now has a use HasApiTokens statement as part of the User model by default, however, it uses the Sanctum implementation and not passport.

So replace:

use Laravel\Sanctum\HasApiTokens;

With:

use Laravel\Passport\HasApiTokens;
  • Related