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

Ionic调用Laravel获取用户信息时Header验证失败问题排查

Ionic 5 + Laravel 9 Passport认证API用户信息拉取失败问题排查

问题场景

在Ionic 5应用与Laravel 9之间搭建Passport认证API,登录后access token已成功发送并存储到Ionic应用,但调用拉取用户信息接口时无响应/无错误,Laravel日志返回授权拒绝错误。

Laravel端代码

public function login(Request $request)
{
    $validator = Validator::make($request->all(), [
        'email' => 'required|string|email|max:255',
        'password' => 'required|string|min:6',
    ]);
    if ($validator->fails()) {
        return response(['errors' => $validator->errors()->all()], 422);
    }
    $user = User::where('email', $request->email)->first();
    if ($user) {
        if (Hash::check($request->password, $user->password)) {
            $token = $user->createToken('Pesacount-User-Access-Token')->accessToken;
            $response = ['token' => $token];
            return response($response, 200);
        } else {
            $response = ["message" => "Password mismatch"];
            return response($response, 422);
        }
    } else {
        $response = ["message" => 'User does not exist'];
        return response($response, 422);
    }
}

public function userInfo() 
{
    $user = auth()->user();
    return response()->json(['user' => $user], 200);
}

Ionic端代码

user() {
    const headers = new HttpHeaders({
        //'Authorization': this.global.token["token_type"] + " " + this.global.token["access_token"]
        'Authorization': 'Bearer ' + this.global.token
    });
    alert('getting user');
    return this.http.get(this.env.API_URL + 'auth/get-user', { headers: headers })
        .pipe(
            tap(user => {
            alert('got uuser');
                return user;
            }),
        )
}

Laravel错误日志

[2022-10-15 08:51:52] local.ERROR: The resource owner or authorization server denied the request. {"exception":"[object] (League\\OAuth2\\Server\\Exception\\OAuthServerException(code: 9): The resource owner or authorization server denied the request. at /var/www/html/Pesacount/vendor/league/oauth2-server/src/Exception/OAuthServerException.php:243)

问题原因及修复方案

核心问题分析

日志中的OAuthServerException(code:9)对应无效或未正确传递的token,结合代码来看,主要是以下几个问题:

1. 路由未配置认证中间件

userInfo方法未添加auth:api中间件,导致Laravel无法验证token。
修复:
在routes/api.php中给对应路由添加中间件:

Route::get('auth/get-user', [AuthController::class, 'userInfo'])->middleware('auth:api');

2. Token传递格式或存储错误

  • Laravel返回的accessToken是纯字符串,前端需确保存储的是该字符串,而非其他结构
  • Authorization头需严格遵循Bearer [token]格式,不能有多余空格或字符
    修复:
    修改Ionic登录逻辑,确保正确存储token:
// 登录请求示例
login(email: string, password: string) {
  return this.http.post(this.env.API_URL + 'auth/login', {email, password}).pipe(
    tap((res: any) => {
      // 直接存储返回的token字符串
      this.global.token = res.token;
    })
  );
}

同时优化请求头构造:

user() {
    const headers = new HttpHeaders({
      'Authorization': `Bearer ${this.global.token.trim()}`,
      'Content-Type': 'application/json'
    });
    return this.http.get(`${this.env.API_URL}auth/get-user`, { headers })
      .pipe(
        tap(user => console.log('用户信息:', user))
      );
}

3. CORS配置导致请求头被拦截

如果Laravel的CORS配置未允许Authorization头,浏览器会自动拦截该请求头,导致后端无法接收token。
修复:
修改config/cors.php:

return [
    'paths' => ['api/*'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'], // 生产环境替换为Ionic应用域名
    'allowed_headers' => ['Content-Type', 'Authorization'],
    'supports_credentials' => true,
];

4. 缓存导致配置未生效

执行以下命令清除Laravel缓存:

php artisan config:clear
php artisan route:clear

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:01:16