Symfony2 App with RESTful authentication, using FOSRestBundle and FOSUserBundle

﹥>﹥吖頭↗ 提交于 2019-11-30 07:32:43
Michal Artazov

I was able to find a simple solution. I only needed to write a class, that implements AuthenticationSuccessHandlerInterface and AuthenticationFailureHandlerInterface.

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);
    }
}

Then I registered it as a service and configured as handlers for the firewall.

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

Problem solved and no complicated authentication provider needed :-)

I understood your problem because I passed by a similar situation but with SOAP services. In the middle I could re-search the security wsse and Symfony2 has already provides a solution

http://symfony.com/doc/current/cookbook/security/custom_authentication_provider.html

It works with a real token and you can match with an user in FOSUserBundle. The only think that I see is the field "password" that you want to compare is the same that in the database (with encryption) then I decided to create a extra field only for this use.

I hope that it help you.

Greetings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!