简体   繁体   English

在公共 REST 上下文中处理 symfony 表单中的 CSRF 令牌

[英]handling the The CSRF token in symfony's forms when in public REST context

I'm developer my first symfony (3) app.我是我的第一个 symfony (3) 应用程序的开发者。 it is a REST service publicly accessible .它是一种可公开访问REST 服务 I'm doing this using FOSRestBundle.我正在使用 FOSRestBundle 执行此操作。 I'll have to ad some admin forms soon or later, and I'll probably want to create them directly (without passing by the extra work of consuming my own web services)我迟早要添加一些管理表单,我可能想直接创建它们(不通过使用我自己的 Web 服务的额外工作)

I wonder how to handle the CSRF token in this case .我想知道在这种情况下如何处理 CSRF 令牌 I see different solutions:我看到不同的解决方案:

  • globally deactivate the CSRF token : I don't want to do this全局停用 CSRF 令牌:我不想这样做
  • create two set of forms, one with the token activated : form my admin forms, the other one for the REST API.创建两组表单,一组激活令牌:形成我的管理表单,另一组用于 REST API。 => in this case, the rest API can't have a fallback _format=html => 在这种情况下,其余 API 不能有后备 _format=html
  • find a way to give the api consumer an auth, with an API_GROUP, and disable the token for this group找到一种方法为 api 使用者提供身份验证,使用 API_GROUP,并禁用该组的令牌
    • it seem to me the best solution, but I don't know how to do it transparently, without affecting the auth of my future admin, and without needing to give credentials in the REST request.在我看来这是最好的解决方案,但我不知道如何透明地做到这一点,而不影响我未来管理员的身份验证,并且不需要在 REST 请求中提供凭据。
  • use an event listener in order to hack symfony's auth mechanism and give an auth if a call is made to the REST API (all but _format=html)使用事件侦听器来破解 symfony 的身份验证机制,并在调用 REST API 时提供身份验证(除 _format=html 外的所有内容)

Which one of this (or other) solution seem the best to you, and how would you code it?这个(或其他)解决方案中的哪一个对您来说是最好的,您将如何对其进行编码?

I found a way, perhaps not the best one, but it works :我找到了一种方法,也许不是最好的方法,但它有效:

$_format = $request->attributes->get('_format');
if ('html' == $_format) {
    $form = $this->createForm(ItopInstanceUserType::class, $itopInstanceUser);
} else {
    $form = $this->createForm(ItopInstanceUserType::class, $itopInstanceUser, ['csrf_protection' => false]);
}

For me, forget CSRF token managed by yourself, check subjects like Oauth authentication.对我来说,忘记自己管理的 CSRF 令牌,检查 Oauth 身份验证等主题。

Take a look here: https://github.com/FriendsOfSymfony/FOSOAuthServerBundle/blob/master/Resources/doc/index.md看看这里: https : //github.com/FriendsOfSymfony/FOSOAuthServerBundle/blob/master/Resources/doc/index.md

FOSOAuthServerBundle works perfectly with FOSRestBundle. FOSOAuthServerBundle 与 FOSRestBundle 完美配合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM