gpt4 book ai didi

php - 具有 RESTful 身份验证的 Symfony2 应用程序,使用 FOSRestBundle 和 FOSUserBundle

转载 作者:可可西里 更新时间:2023-11-01 13:39:59 25 4
gpt4 key购买 nike

我正在为我的 JS 驱动应用制作 REST API。

在登录期间,登录表单通过 AJAX 提交到我的 API 的 url /rest/login

  • 如果登录成功,返回204
  • 如果失败,返回401

虽然我为 API 和应用程序本身分离了防火墙,但它们共享相同的上下文,这应该意味着,当用户针对 API 进行身份验证时,他也针对应用程序进行了身份验证。因此,当服务器返回 204 时,页面将重新加载并且它应该将用户重定向到应用程序,因为他现在已经登录。

我尝试使用 FOSUserBundle 的预制 check_login 页面并指向那里的 /rest/login

login:
path: /rest/login
defaults:
_controller: FOSUserBundle:Security:check
methods: [ POST ]

那是行不通的,因为无论如何它总是返回重定向。我阅读了 symfony 的文档,但找不到如何制作自定义 check_login 页面。我需要的是这样的东西

use Symfony\Component\Security\Core\Exception\AuthenticationException;
use FOS\RestBundle\Controller\Annotations\View;

class SecurityController {

/**
* @View(statusCode=204)
*/
public function loginAction($username, $password) {

/* first I need to somehow authenticate user
using normal authentication, that I've set up */
...

/* Then I need to return 204 or throw exception,
based on result.
This is done using FOSRestBundle and it's
listeners. */

if(!$succesful) {
throw new AuthenticationException();
}
}
}

我不知道该怎么做。我在任何文档中发现的任何内容都对我没有帮助。如果能给我指明正确方向的任何建议,我将不胜感激。


编辑:为了进一步简化,我的目标是什么。我希望我的登录功能与普通 form_login 完全相同。我只想更改它发回的响应 - 而不是重定向,我希望成功时返回 204,失败时返回 401。

最佳答案

我找到了一个简单的解决方案。我只需要编写一个实现 AuthenticationSuccessHandlerInterfaceAuthenticationFailureHandlerInterface 的类。

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;

class AuthenticationRestHandler implements AuthenticationSuccessHandlerInterface, AuthenticationFailureHandlerInterface {

public function onAuthenticationFailure(Request $request, AuthenticationException $exception) {
return new Response('', Response::HTTP_UNAUTHORIZED);
}

public function onAuthenticationSuccess(Request $request, TokenInterface $token) {
return new Response('', Response::HTTP_NO_CONTENT);
}
}

然后我将其注册为服务并配置为防火墙的处理程序。

services:
security.authentication_rest_handler:
class: AuthenticationRestHandler

security:
firewalls:
rest:
pattern: ^rest
context: app
form_login:
check_path: /rest/login
provider: fos_userbundle
failure_handler: inspireon.security.authentication_rest_handler
success_handler: inspireon.security.authentication_rest_handler
username_parameter: login
password_parameter: password

问题已解决,不需要复杂的身份验证提供程序:-)

关于php - 具有 RESTful 身份验证的 Symfony2 应用程序,使用 FOSRestBundle 和 FOSUserBundle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28075078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com