user

Joseph Morgan

16 Jul 2022

Increase Sanctum token length in Laravel x9

Laravel

How to Increase Sanctum token length in Laravel 9?
this is my login function which generate the token 

<?php
 if(Auth::attempt(['email' => request('email') , 'password' => request('password')])){
 $token = Auth::user()->createToken('authentication')->plainTextToken;
 $lastLogin = User::find(Auth::user()->id);
 $lastLogin->last_login = Carbon::now()->format('Y-m-d\TH:i:s.vP');
 $lastLogin->save();
 return response()->json([ "user" => Auth::user(), "token" => $token ], 200);
 } else {
 return response()->json(['Error, Wrong email or password'], 400); 
 }
 ?>

and the token which generated by this function is too small 

5|FHtT0lg8w3AxJvIGYhxVf2PBYuGjgw3xALYDqkr8

How can I generate it like the Regular Bearer token? Any solution please

 

Comments

Mohamed Atef

16 Jul 2022

Best Answer

best answer
githubgithubgithub

Yes i believe you can do this, using this function in your User module 

<?php
 public function createToken(string $name, array $abilities = ['*']){
 $token = $this->tokens()->create([
 'name' => $name,
 'token' => hash('sha256', $plainTextToken = Str::random(200)),
 'abilities' => $abilities,
 ]);

 return new NewAccessToken($token, $token->getKey().'|'.$plainTextToken);
 }

and don't forget to use 

use Illuminate\Support\Str;
use Laravel\Sanctum\NewAccessToken;

at the top of your Module

Replies

Joseph Morgan

16 Jul 2022

Thank you, I will try this function

© 2024 Copyrights reserved for web-brackets.com