skip to Main Content

I’m using Laravel 10 and Laravel Passport and in this project, I tried registering new users like this:

public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|unique:users|max:255',
            'password' => 'required|min:6'
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password)
        ]);

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

        return response([
            'token' => $token
        ]);
    }

Then I defined another route which is under api middleware:

Route::post('register',[AuthenticationController::class,'register']);

Route::middleware('auth:api')->group(function() {
    Route::resource('products', ProductController::class);
});

And in the ProductController I tried adding this method for storing new products:

public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|max:255',
            'description' => 'required|max:255',
            'price' => 'required'
        ]);

        if ($request->user()) {
            Product::create([
                'title' => $request->title,
                'description' => $request->description,
                'price' => $request->price,
                'user_id' => $request->user()->id
            ]);

            return response([
                'message' => 'product created successfully'
            ],201);
        }else{
            return response(['message' => 'User not authenticated.'], 401);
        }
    }

But when I test the url in PostMAN which is this:

http://localhost:8000/api/products

I get this message:

{
    "message": "Unauthenticated."
}

However I have copied and pasted the token retrieved from /register rendpoint as Token input of Authorization section:

enter image description here

I also set the Headers to Accept and application/json and sent these form-data as Body:

title:myproduct
description:The production desc
price:2000

I don’t know why I get this Unauthenticated Message, I also configured the auth.php like this:

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

And added this Service Provider to app.php:

LaravelPassportPassportServiceProvider::class,

And used the correct class at User Model:

use LaravelPassportHasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
    ...
}

So what’s going wrong here? How can I solve this issue?


UPDATE #1:

Result of dd($user->createToken('MyApp'));:

enter image description here

2

Answers


  1. It looks like you are passing the token incorrectly in Postman when you select Bearer Token from the authorization tab as type. You don’t have to add Bearer before your token in this case, that is why your token is getting mismatched. Check the below screenshot of how the string Bearer is getting prepended twicce to your access token.

    enter image description here


    Instead, you just need to add the access token to the value which should solve the issue.

    enter image description here

    Login or Signup to reply.
  2. I think you are not retrieving your token correctly. You must provide this value to the user

      $token = $user->createToken('MyApp')->plainTextToken;
    

    so you can do this

          $token = $user->createToken('MyApp')->plainTextToken;
    
            return response([
                'token' => $token
            ]);
    

    If you then use that $token string value as your BearerToken you should be fine.

    As a good rule of thumb you should check that your plain text token starts with a number.

    eg

    29|NFAXFH5HRbZtdM1knfHTRXpB8VmVYkIlCELOB3ef0daf95da

    The plain text token is not stored in your database

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search