You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 5.5 auth:api配置:使用Header中的Bearer Token鉴权

How to Switch Laravel 5.5 API Auth to Use Bearer Tokens in Authorization Header

Hey there! Great job getting your first Laravel API endpoint up and running. The good news is Laravel 5.5's auth:api middleware actually supports Bearer tokens in the Authorization header out of the box—you might just need to double-check a few things to get it working, or tweak it if you want to only accept header-based tokens.

Step 1: Verify Your Authentication Configuration

First, make sure your config/auth.php is set up correctly for token authentication. Open the file and check the guards section for the api guard:

'guards' => [
    'api' => [
        'driver' => 'token',
        'provider' => 'users',
        'hash' => false, // Leave as false if you're storing plain-text tokens (default for 5.5)
    ],
],

This is the default setup, and it tells Laravel to use the TokenGuard for API authentication. By default, this guard checks three places for the token:

  • The Authorization: Bearer {token} request header
  • The api_token URL parameter (which is what you're using now)
  • The api_token field in the request body

So if your config looks like this, you should already be able to use the header approach. Let's test it.

Step 2: Test the Bearer Token Request

Use a tool like curl, Postman, or Insomnia to send a request with the correct header. For example, with curl:

curl -H "Authorization: Bearer 123" http://localhost/my-endpoint

Make sure you include the space after Bearer—that's a common mistake! If this works, you're all set. You can now use either the URL parameter or the header (unless you want to restrict it to only headers, which we'll cover next).

Step 3: (Optional) Restrict to Only Bearer Tokens (Disable URL Parameter)

If you want to stop accepting the api_token URL parameter and only allow the Authorization header, you'll need to create a custom guard that overrides the token retrieval logic.

  1. Open app/Providers/AuthServiceProvider.php and update the boot method to register your custom guard:
use Illuminate\Auth\TokenGuard;
use Illuminate\Support\Facades\Auth;

public function boot()
{
    $this->registerPolicies();

    // Register a custom guard that only accepts Bearer tokens
    Auth::extend('api_bearer_only', function ($app, $name, array $config) {
        // Get the user provider configured in auth.php
        $provider = Auth::createUserProvider($config['provider']);

        // Extend the default TokenGuard to only check the Authorization header
        return new class($provider, $app['request']) extends TokenGuard {
            public function getTokenForRequest()
            {
                // Only return the token from the Bearer header
                return $this->request->bearerToken();
            }
        };
    });
}
  1. Update your config/auth.php to use this new guard for the api guard:
'guards' => [
    'api' => [
        'driver' => 'api_bearer_only', // Use our custom guard
        'provider' => 'users',
        'hash' => false,
    ],
],

Now, any request using the api_token URL parameter will fail authentication—only the Authorization: Bearer {token} header will work.

Quick Troubleshooting

  • If the header request isn't working, double-check that your token matches the api_token value in your users database row.
  • Ensure there are no other middleware modifying or stripping the Authorization header (like CORS middleware—if you're testing from a frontend, make sure your CORS setup allows the header).
  • Confirm you're using the correct syntax for the header: Authorization: Bearer YOUR_TOKEN_HERE (capitalization matters for the header name in some servers).

内容的提问来源于stack exchange,提问作者StyleSh1t

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:13:54