feat(auth): implement API key authentication and enhance request handling
- Add AuthGuard to validate API key for public access. - Create AuthModule to provide the AuthGuard globally. - Update API request interceptor to automatically include API key for non-localhost requests. - Modify .env and .env.example to include API_KEY configuration. - Enhance API request handling with improved error logging and client IP detection.
This commit is contained in:
@@ -1,34 +1,52 @@
|
||||
import axios from 'axios'
|
||||
import axios, { type AxiosRequestConfig, type AxiosError } from 'axios';
|
||||
|
||||
/**
|
||||
* API配置
|
||||
* 配置axios实例,设置baseURL和请求拦截器
|
||||
*/
|
||||
const api = axios.create({
|
||||
baseURL: 'http://localhost:3000', // 设置后端服务地址
|
||||
baseURL:
|
||||
(import.meta.env.VITE_API_BASE_URL as string) || 'http://localhost:3000', // 设置后端服务地址
|
||||
timeout: 120000, // 请求超时时间(120秒)
|
||||
})
|
||||
});
|
||||
|
||||
// 请求拦截器
|
||||
api.interceptors.request.use(
|
||||
(config) => {
|
||||
// 可以在这里添加认证信息等
|
||||
return config
|
||||
(config: AxiosRequestConfig) => {
|
||||
// 如果 baseURL 不是 localhost,自动添加 API Key
|
||||
const baseURL =
|
||||
(config.baseURL as string) ||
|
||||
(api.defaults.baseURL as string) ||
|
||||
'';
|
||||
const isLocalhost =
|
||||
baseURL.includes('localhost') || baseURL.includes('127.0.0.1');
|
||||
|
||||
if (!isLocalhost) {
|
||||
// 从环境变量或 localStorage 获取 API Key
|
||||
const apiKey =
|
||||
(import.meta.env.VITE_API_KEY as string) ||
|
||||
localStorage.getItem('apiKey');
|
||||
if (apiKey && config.headers) {
|
||||
config.headers['X-API-Key'] = apiKey;
|
||||
}
|
||||
}
|
||||
|
||||
return config;
|
||||
},
|
||||
(error) => {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
(error: AxiosError) => {
|
||||
return Promise.reject(error);
|
||||
},
|
||||
);
|
||||
|
||||
// 响应拦截器
|
||||
api.interceptors.response.use(
|
||||
(response) => {
|
||||
return response
|
||||
return response;
|
||||
},
|
||||
(error) => {
|
||||
console.error('API请求错误:', error)
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
(error: AxiosError) => {
|
||||
console.error('API请求错误:', error);
|
||||
return Promise.reject(error);
|
||||
},
|
||||
);
|
||||
|
||||
export default api
|
||||
export default api;
|
||||
Reference in New Issue
Block a user