简体   繁体   中英

Laravel Passport Print Personal Access Token

I am using Laravel's passport package to provide token based authentication to my rest api. Right now, I am using personal access token concept to generate the access token.

To generate an access token for a single user, I am using below code to generate a token with name ' android '.

    $user = User::create([
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => bcrypt($data['password']),
            ]);

    // Here the access token will be stored in $token variable.
    $token = $user->createToken('android')->accessToken;

    // Now the $token value would be something like
   //eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImMyNjI3YzU0YjFhNWIxZTFlMTdkODhmZTk1NzhjNzAzY2QyMTU0MzhlOD...

Later on I want to display the personal access token on my admin dashboard which I am facing difficulty in getting the generated token again. Tried below code, but couldn't able to get the access token.

$user = User::find(1)
dd($user->tokens())

I also tried using passport vue elements, but it is displaying just the access token name, not the actual token.

<passport-personal-access-tokens></passport-personal-access-tokens>

Please help me getting this solved.

Thank you

I think you should just generate the token before or at the same time as you're creating a user and store it in the database:

Add the column:

$table->string('token', 60)->unique();

Save the token:

$token = $user->createToken('android')->accessToken;

$user = User::create([
    'name' => $data['name'],
    'email' => $data['email'],
    'password' => bcrypt($data['password']),
    'token' => $token,
]);

Then it will be available as:

$user->token;

i have face similar problem with laravel & vue js ii updated my middleware handler allow to access Authorization token. it working find for me. some time it will be help Laravel Passport 401 Unauthorized Error using Apache and Vue

You can try the following code:

    $user->tokens->load('client')->filter(function ($token) {
        return ! $token->client->firstParty() && ! $token->revoked;
    })->values();

I had the same problem and it was weird that it was so hard to fetch the token that the client should use. I also felt weird to store the token to the database, I was thinking that I am duplicating data in a way.

So after a lot of research I tweaked a Trait and I now can have exactly that.

Check this gist it may solve your problem as well.

You can't retrieve access_token directly. Because, when you create access token $token = $user->createToken('android')->accessToken; , Laravel Passport will create access_token and it is not directly store into database. Instead, it is store that access_token 's id(called Json Token Id) into oauth_access_tokens table.

So, when you search access_token directly in oauth_access_tokens table, you will never find that access_token , only you can see its Json Token Id .

Eg: access_token: eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiNTMxYTAyYTBkMjA4N2MyZWI3NDU1MWM0NzkzZGM3OTJkYWM3ZmRmYTcyOTVjZGI1NWNjMDg4NDFiMDUyZTc5M2ViMTE5NDg3ZmNhYWUxODciLCJpYXQiOjE2MjMxMjU3MjYuNjgyMzE2LCJuYmYiOjE2MjMxMjU3MjYuNjgyMzIsImV4cCI6MTY1NDY2MTcyNi42NzQwMzYsInN1YiI6IjQiLCJzY29wZXMiOltdfQ.hCfn7mPgrNoD-kHXjgXawoil50jBzh78s_7MBq-GRUOD7fNKzEn-24mHT_qppu5v-TAlJSww0iR-zPCe82_FB4JlmR0D1ERwVdX_DD1wKcn2DR9mhCKdB8XNLsu4MZMqhPahO7ft2mC8Hu7lM6zhfgKiAkiNsR68zUbCLYB7_h82T-ef5Xp6Lp61wfSq_KATVpEkv59jp62PSdNyF3SLPT5bqfOOwziJxv2lMW1Y61M4WY_3f4prwVfA81qo_XkczBC4b9-j36ly7YluzbVHRQnNGzTRkekv8fuv4Q3USRdRkWDFR2lTJ9zz31LEN8jbnY9hoAkvE57KyEyJ3qfUzkoYFXaAIF9VQe6j8TtNGOehiAf9uQm049m0zopL5w-g4u5qulJeYp0OEgfq6nK8DtuAERSgEAeY2kINqbLenhywwJmX70mrF_BqfxaZS7MIomyybOWi6FVHj4WXA8OIPgrUUu2BAtgwdCtt-ECN6svCvBLV15nBXi6OPpbSFbbV2Ve4fy2kGH5dWUfKZe0W6Cai0Uux_lUVDSx6q6bo4bf5_67Twg2E7EI4CpzyCk7g_ZG3Ff3vdTTs8P5f0LIHihCjCp6c_cuLnws8laD1L1-rqBmCQSZ7ZGeI-LYouWEbtXnf6M4xlfJoubXZGiTi8Zun9X2EhgRR8XjviOWM8AU

Its Json Token Id: 87dcc72560f41406d6cec1f35a66c24ac65953f2e8b28401e06e282c340eba7ef2c2fee65a0a0519

This was my solution.

I created a configure passport migration to install the client and modify the name column in the oauth_access_tokens table to longtext, so i could use it to store the access token in.

public function up()
{
    /*
     * This command will create the encryption keys needed to generate secure access tokens.
     * In addition, the command will create "personal access" and "password grant"
     * clients which will be used to generate access tokens
     */
    Artisan::call( 'passport:install', array('-n' => true) );

    // Set the type to LONGTEXT so we can store the access token in it
    Schema::table( 'oauth_access_tokens', function ($table) {

        $table->string( 'name', 4294967295 )->change();
    });
}

Then i added the following method to my user model.

/**
 * Get the users api access token.
 */
public function getAccessToken() {

    $existingToken = $this->tokens()->where( 'revoked', false )->first();

    if ( $existingToken ) {

        return $existingToken->name;
    }

    $accessToken = $this->createToken( $this->uuid )->accessToken;

    // save the access_token so we can recycle it.
    $this->tokens()->where( 'revoked', false )->update( [
        'name' => $accessToken,
    ] );

    return $accessToken;
}

then in my transformer i can call it to retrieve the users access token, or create one.

/**
 * A Fractal transformer.
 *
 * @param User $user
 * @return array
 */
public function transform(User $user) {

    return [
        'access_token' => $user->getAccessToken(),
    ];
}

I have also faced the same problem. And I solved it with a command which described here in laravel documentation . Just go to php project and create a client for passport, open up your terminal or cmd and execute the command php artisan passport:install .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM