1
votes

I am trying to utilize Sanctum for an API only application. I am not using it for a SPA. I have a single end point set up and protected by the Sanctum middleware. I am creating a user and a token for said user through the tinker cli tool. I then paste the token into Postman under the bearer token selection within the authorization tab. However, when I submit the request I get an unauthenticated error. Not quite sure what I am doing incorrect here. Followed the documentation provided very closely as well as the sparse videos I could find. Here are some code snippets. I appreciate the insight here.

API.php

Route::middleware('auth:sanctum')->apiResource('/documents','DocumentHandlerController');

Middleware/Authenticate.php

class Authenticate extends Middleware
{
    /**
     * Return 401 when not authorized
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    public function handle($request)
    {
        return response()->json(
            ['message'=>'Unauthorized']
            ,Response::HTTP_UNAUTHORIZED
        );
    }
}

Function from my controller

    public function index()
    {
        return response()->json(['Success'],Response::HTTP_OK);
    }
3
I stand under correction here but I experienced a similar issue to you a few weeks back. What I THINK the issue is that Sanctum makes use of cookie-based auth and requires the CSRF protection and stateful management in the web.php. Are you using the sanctum cookie auth or are you making use of api tokens in this instance? I eventually resolved this issue by making use of the web.php instead of the api.php. Im not sure how helpful this is but that worked for meD. Jones
can you explain, how did you create token?Hamid Shariati

3 Answers

1
votes

Faced with the same problem. After some investigation it seems the problem happens there: https://github.com/laravel/sanctum/commit/f5695aecc547138c76bc66aaede73ba549dabdc5

During the refactoring they forgot to include default guard definition.

Just add this at the end of config/sanctum.php for api guard:

'guard' =>  'api'
1
votes

I faced the same Issue but I solved it by add to headers: Accept with value application/json.

That's the best solution I found maybe others have another solution.

enter image description here

0
votes

For some reason auth:sanctum doesn't work for API authentication. Same problem happened with me then i saw this issue on github .
i see two solutions at this point

  1. jwt-auth
  2. API Authentication