如何在请求头中向服务器发送JSON Web Token(JWT)
Hey there! Let's break down the most widely used, standard methods to send a JWT in request headers—this is way more straightforward than the niche httpChannel approach you found on MDN.
The Universal Standard: Authorization Header with Bearer Scheme
This is the industry-standard way to send JWTs, supported by every major HTTP client and backend framework. The format is simple:
Authorization: Bearer
Below are examples for common client environments:
JavaScript (Browser/Node.js)
- Using native
fetch:
const jwtToken = 'your-generated-jwt-token'; fetch('https://your-api-endpoint.com/protected', { method: 'GET', headers: { 'Authorization': `Bearer ${jwtToken}` } }) .then(response => response.json()) .catch(error => console.error(error));
- Using
axios(more popular for API calls):
const jwtToken = 'your-generated-jwt-token'; axios.get('https://your-api-endpoint.com/protected', { headers: { 'Authorization': `Bearer ${jwtToken}` } }) .then(response => console.log(response.data)) .catch(error => console.error(error));
PHP (Client-Side Requests)
If you're sending requests from PHP (e.g., calling your own API), here are two common approaches:
- With
curl:
$jwtToken = 'your-generated-jwt-token'; $ch = curl_init('https://your-api-endpoint.com/protected'); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Authorization: Bearer {$jwtToken}" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch);
- With Guzzle (a popular PHP HTTP client):
use GuzzleHttp\Client; $jwtToken = 'your-generated-jwt-token'; $client = new Client(); $response = $client->request('GET', 'https://your-api-endpoint.com/protected', [ 'headers' => [ 'Authorization' => "Bearer {$jwtToken}" ] ]);
Command Line (curl)
For testing or CLI workflows:
curl -H "Authorization: Bearer your-generated-jwt-token" https://your-api-endpoint.com/protected
Why httpChannel Isn't Common
The httpChannel method you saw on MDN is specific to legacy browser extension environments (like old Firefox add-ons using the XUL SDK). It's not relevant for regular web apps, mobile apps, or standard API interactions—stick with the Bearer scheme for universal compatibility.
Quick Tip for PHP Backend Handling
Since you mentioned working with a PHP JWT class, here's a quick snippet to extract the token from the header in your server code:
// Retrieve the Authorization header $authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? ''; // Extract the JWT by removing the "Bearer " prefix if (preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) { $jwtToken = $matches[1]; // Pass this token to your JWT class for validation } else { // No valid token provided http_response_code(401); echo json_encode(['error' => 'Unauthorized']); }
内容的提问来源于stack exchange,提问作者Ramesh Pareek

