Home > front end >  Displaying Authenticated User Using Laravel Sanctum Api
Displaying Authenticated User Using Laravel Sanctum Api

Time:12-04

I want to display the data of the authenticated user and also produce a status code and a status message when the user is not authenticated. I am using Laravel API and Sanctum and this is what I have tried:

public function me(Request $request){    
    
    $user = $request->user();

    if($user)
    {
    return response()->json([
        'status'=>200,
        'user'=>$user
    ]);
    
} else {
    return response()->json([
        'status'=>401,
        'message'=>'No access'
    ]);
}

}

Problem is, it displays the status 200 when authenticated and does not display the status 401 code when not. It only displays the default Sanctum

{
"message": "Unauthenticated."
}

There is also a bearer token involved in the authentication. Kindly help

CodePudding user response:

First, you need to check if the user is authenticated by using the $request->user() method. If it returns null, it means the user is not authenticated and you can return the appropriate response with a status code of 401 and the error message.

To check if the user is authenticated, you can use the Auth::check() method in Laravel, like this:

public function me(Request $request){    
    
    if(Auth::check())
    {
        $user = $request->user();

        return response()->json([
            'status'=>200,
            'user'=>$user
        ]);

    } else {
        return response()->json([
            'status'=>401,
            'message'=>'No access'
        ]);
    }

}

Alternatively, you can also use the $request->user() method and check if it returns a null value, like this:

public function me(Request $request){    
    
    $user = $request->user();

    if($user)
    {
        return response()->json([
            'status'=>200,
            'user'=>$user
        ]);

    } else {
        return response()->json([
            'status'=>401,
            'message'=>'No access'
        ]);
    }

}

In both cases, if the user is not authenticated, it will return a response with a status code of 401 and the error message "No access".

CodePudding user response:

If you confirmed that the token already involved in Authorization header, maybe you need to check some of this step:

You need to verify that in your User model already add HasApiTokens from package Laravel\Sanctum\HasApiTokens.

After that, you can check the router middleware. You can use middleware auth:sanctum for protected endpoint. If you were using middleware ability, maybe you can check it too.

Go to config/cors.php, enable supports_credentials to true.

If you tried it before using your Frontend apps, have you try it with postman ?

  • Related