CSRF令牌不匹配Laravel圣所和Angular http [英] CSRF token mismatch Laravel sanctum and Angular http

查看:179
本文介绍了CSRF令牌不匹配Laravel圣所和Angular http的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试实现Laravel Sanctum,但是即使遵循了Laravel Sanctum文档中的所有说明,我仍然遇到错误"CSRF令牌不匹配"

I have been trying to implement Laravel sanctum, but I am having this error "CSRF token mismatch" even though I followed everything that is said in the Laravel Sanctum documentation

cors.php配置文件

'paths' => [
    'api/*',
    'login',
    'logout',
    'sanctum/csrf-cookie'
],
'supports_credentials' => true,

kernal是根据文档添加的,因此不要在此处添加代码来浪费空间

kernal is added as per the documentation, so not wasting space by adding its code here

.env文件

SESSION_DRIVER=cookie
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost

我在这里使用Angular 9作为我的前端

I am using Angular 9 as my frontend here

这是我的拦截器

request = request.clone({
    withCredentials: true
})

这是我将请求发送给Laravel的方式

This is how I send the request to Laravel

this.http.get<any>(url('sanctum/csrf-cookie')).subscribe(() => {
     this.http.post<any>(url('login'), { this.username, this.password })
         .subscribe(success => console.log(success), error => console.log(error))
})

点击第一条路径后,我可以确认创建cookie,但是问题出在第二条路径('/login')上

Once the first route is hit I can confirm the creation of cookies, but the issue is with the second route ('/login')

推荐答案

您需要发送 x-csrf-token (Angular仅在相对URL中自动包含它,而不是绝对URL)

You need to send x-csrf-token in the header, (Angular includes it automatically only in relative URLs not absolute)

您可以创建一个解释器来执行此操作,类似这样的方法应该起作用:

You can create an interpreter to do this, something like this should work:

import {Injectable} from '@angular/core';
import {
  HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpXsrfTokenExtractor
} from '@angular/common/http';

import { Observable } from 'rxjs';

@Injectable()
export class HttpXsrfInterceptor implements HttpInterceptor {
  headerName = 'X-XSRF-TOKEN';

  constructor(private tokenService: HttpXsrfTokenExtractor) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    if (req.method === 'GET' || req.method === 'HEAD') {
      return next.handle(req);
    }

    const token = this.tokenService.getToken();

    // Be careful not to overwrite an existing header of the same name.
    if (token !== null && !req.headers.has(this.headerName)) {
      req = req.clone({headers: req.headers.set(this.headerName, token)});
    }
    return next.handle(req);
  }
}

这篇关于CSRF令牌不匹配Laravel圣所和Angular http的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆