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

Angular通过JWT注册遇ActionController::InvalidAuthenticityToken错误求助

解决Angular注册时的ActionController::InvalidAuthenticityToken错误

这个错误来自Rails后端,它要求非GET请求携带CSRF(跨站请求伪造)令牌保障安全,和JWT无关——JWT是注册成功后用于后续认证的凭证,注册阶段还没有JWT可以发送。下面是具体修复步骤:

步骤1:获取Rails的CSRF令牌

Rails会在页面的<meta>标签中注入CSRF令牌,你可以在Angular中通过DOM获取该值:

const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');

步骤2:在注册请求中添加CSRF令牌头

修改你的注册服务代码,在POST请求里带上X-CSRF-Token请求头:

public signUp(name: string, password: string): Observable<IEmployee> {
  const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
  const headers = new HttpHeaders().set('X-CSRF-Token', csrfToken || '');
  
  return this.http.post<IEmployee>(`${environment.apiUrl}/sign_up.json`, 
    {name, password },
    { headers }
  );
}

额外注意事项

  • 若你的Rails后端是纯API应用,可在对应控制器或全局配置中关闭CSRF保护:
    skip_before_action :verify_authenticity_token
    
    但仅建议在确认API不会被浏览器端请求访问时使用,否则会降低安全性。
  • 你的表单收集了phoneNumber字段,但注册时未传递给后端,需补充该参数:
    // 在sign-up component的onRegistration方法中
    const { name, password, phoneNumber } = this.formRegistration.value;
    this.store.dispatch(new SignUp(name, password, phoneNumber));
    // 同时更新SignUp action和服务的signUp方法,接收并传递phoneNumber参数
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 20:10:43