symfony 3.4 webservice userprovider令牌为空

时间:2018-02-01 11:35:50

标签: php symfony authentication token provider

我是symfony开发的新手。我需要通过restapi验证连接来进行连接。

使用restapi恢复登录名和密码一切顺利。 如果我输入了一个错误的密码,那么凭证不好。 如果我输入一个好密码,那么我会在登录页面上循环。

令牌似乎是空的,我总是被匿名识别而不使用它。

这是我的代码:

应用程序/配置/ securtiy.yml

security:
    providers:
        monwebservice:
            id: CO\UserBundle\Security\User\WebserviceUserProvider       
    encoders:
        CO\UserBundle\Security\User\WebserviceUser: plaintext

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        main_login:
            pattern:   ^/login$
            #provider: monwebservice
            anonymous: true

        main:
            pattern:   ^/
            anonymous: false
            logout: ~
            provider: monwebservice
            form_login:
              login_path: login
              check_path: login_check
              use_referer: true
              default_target_path: co_platform_home
              always_use_default_target_path: true

    role_hierarchy:
        ROLE_ADMIN:       [ROLE_USER]
        ROLE_SUPER_ADMIN: [ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]        
    access_control:
        - { path: ^/platform, roles: ROLE_USER }
        - { path: ^/login$, roles: IS_AUTHENTICATED_ANONYMOUSLY }

应用程序/配置/ routing.yml中

co_user:
    resource: "@COUserBundle/Resources/config/routing.yml"
    prefix:   /

co_platform:
    resource: "@COPlatformBundle/Resources/config/routing.yml"
    prefix:   /platform

login:
    path: /login
    defaults:
        _controller: COUserBundle:Security:login

login_check:
    path: /login_check

recover_check:
    path: /recover_check
    defaults:
        _controller: COUserBundle:Security:recover

register_check:
    path: /register_check

logout:
    path: /logout

的src / CO / UserBundle /安全性/用户/ WebserviceUserProvider.php

namespace CO\UserBundle\Security\User;

use CO\UserBundle\Security\User\WebserviceUser;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;

class WebserviceUserProvider implements UserProviderInterface
{
  private $container;

  public function __construct(Container $container)
  {
    $this->container=$container;
  }

  public function loadUserByUsername($username)
  {
    $request = $this->container->get('request_stack')->getMasterRequest();
    $password=$request->request->get('_password');

    if($password=="" || $username=="") {
      throw new UsernameNotFoundException('Field is empty !');
    }
    // make a call to your webservice here
    $api = $this->container->get('co_api.restapi');
    $passOk=false;
    if($api->init()===true) {
      ////CODE REST////
      $passOk=true;
    }

    if($passOk===true) {
        $salt="";
        $roles=array('ROLE_USER');
        $clUser = new WebserviceUser($username, $password, $salt, $roles);
        return $clUser;

    }
    throw new UsernameNotFoundException(
        sprintf('Username "%s" does not exist.', $username)
    );
  }

  public function refreshUser(UserInterface $user)
  {
    if (!$user instanceof WebserviceUser) {
        throw new UnsupportedUserException(
            sprintf('Instances of "%s" are not supported.', get_class($user))
        );
    }

    return $this->loadUserByUsername($user->getUsername());
  }

  public function supportsClass($class)
  {
    return WebserviceUser::class === $class;
  }

}

的src / CO / UserBundle /安全性/用户/ WebserviceUser.php

namespace CO\UserBundle\Security\User;

use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\EquatableInterface;

class WebserviceUser implements UserInterface, EquatableInterface
{
    private $username;
    private $password;
    private $salt;
    private $roles;

    public function __construct($username, $password, $salt, array $roles)
    {
        $this->username = $username;
        $this->password = $password;
        $this->salt = $salt;
        $this->roles = $roles;
    }

    public function getRoles()
    {
        return $this->roles;
    }

    public function getPassword()
    {
        return $this->password;
    }

    public function getSalt()
    {
        return $this->salt;
    }

    public function getUsername()
    {
        return $this->username;
    }

    public function eraseCredentials()
    {
    }

    public function isEqualTo(UserInterface $user)
    {
        if (!$user instanceof WebserviceUser) {
            return false;
        }
        if ($this->password !== $user->getPassword()) {
            return false;
        }
        if ($this->salt !== $user->getSalt()) {
            return false;
        }
        if ($this->username !== $user->getUsername()) {
            return false;
        }
        return true;
    }
}

的src / CO / UserBundle /控制器

namespace CO\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Routing\Annotation\Route;

class SecurityController extends Controller
{
  private $logger;

  public function __construct()
  {
  }

  /**
   * @Route("/login", name="login")
   */  
  public function loginAction(Request $request, AuthenticationUtils $authenticationUtils)
  {
    //$user   = $this->get("security.token_storage")->getToken();
    //print_r($user);

    if ($this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
      return $this->redirectToRoute('co_platform_home');
    }

    return $this->render('COUserBundle:Security:login.html.twig', array(
      'last_username' => $authenticationUtils->getLastUsername(),
      'error'         => $authenticationUtils->getLastAuthenticationError(),
    ));
  }

}

希望你有一个解决方案。 请注意,代码已经工作了一段时间,但因为他不想再识别我了。

1 个答案:

答案 0 :(得分:0)

我的问题(使用authentification webservice)是:

  • 令牌已创建,但已使用匿名令牌擦除并返回登录页面,为什么?
  • 使用in_memory或数据库进行身份验证:它没问题,但无法运行。

composer.json:

"require": {
    "php": ">=5.5.9",
    "csa/guzzle-bundle": "^2.2",
    "doctrine/doctrine-bundle": "^1.6",
    "doctrine/doctrine-fixtures-bundle": "~3.0.2",
    "doctrine/orm": "^2.5",
    "incenteev/composer-parameter-handler": "^2.0",
    "jms/serializer-bundle": "^2.3",
    "sensio/distribution-bundle": "^5.0.19",
    "sensio/framework-extra-bundle": "^5.0.0",
    "stof/doctrine-extensions-bundle": "^1.3",
    "symfony/monolog-bundle": "^3.1.0",
    "symfony/polyfill-apcu": "^1.0",
    "symfony/swiftmailer-bundle": "^2.6.4",
    "symfony/symfony": "3.4.*",
    "twig/twig": "^1.0||^2.0"
}

请帮助我,如果登录无效,我就无法使用symfony。