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

如何在Laravel 9中隐藏Unsplash API密钥

解决Vue前端调用Unsplash API暴露Client-ID的问题

前端直接发起请求时,请求头里的Authorization字段会被浏览器开发者工具捕获,完全无法隐藏。正确的做法是用Laravel作为中间代理层,把Unsplash的Client-ID存放在服务器端,前端只和自己的后端交互。

步骤1:创建Laravel代理路由和控制器

  1. 在routes/api.php中添加支持路径转发的代理路由:
Route::get('/unsplash-proxy/{path?}', [UnsplashProxyController::class, 'fetch'])->where('path', '.*');

({path?}和路由规则用来适配Unsplash API的不同接口路径,比如/photos、/search/photos等)

  1. 生成代理控制器:
php artisan make:controller UnsplashProxyController
  1. 在控制器中编写请求转发逻辑:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class UnsplashProxyController extends Controller
{
    public function fetch(Request $request)
    {
        $clientId = env('UNSPLASH_CLIENT_ID');
        // 拼接完整的Unsplash API请求地址
        $apiUrl = 'https://api.unsplash.com/' . ltrim($request->path(), '/');
        
        // 转发请求并携带认证头,同时传递前端的查询参数
        $response = Http::withHeaders([
            'Authorization' => "Client-ID {$clientId}"
        ])->get($apiUrl, $request->query());
        
        // 返回Unsplash的原始响应内容和状态码
        return response()->json($response->json(), $response->status());
    }
}

步骤2:配置环境变量

在项目根目录的.env文件中添加你的Unsplash Client-ID:

UNSPLASH_CLIENT_ID=你的实际Client-ID值

步骤3:修改Vue组件的请求逻辑

把前端直接请求Unsplash API的代码,改成调用自己的Laravel代理接口:

const myAsync = async function fetchUnsplash() {
  // 调用后端代理接口,无需在前端暴露任何密钥
  const response = await fetch('/api/unsplash-proxy/photos'); // 可根据需求替换具体API路径
  const data = await response.json();
  // 后续数据处理逻辑
};

补充说明

  • 这种方式下,Authorization字段只会出现在服务器端向Unsplash发起的请求中,前端完全看不到密钥信息。
  • 可以根据需求扩展代理逻辑,比如添加请求缓存、参数校验、请求频率限制等,进一步提升安全性和性能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 13:55:17