在具有API身份验证的表单中使用Silex SecurityServiceProvider

时间:2016-04-27 08:56:08

标签: php symfony security silex

我正在尝试通过表单对某些用户进行身份验证,但是我想检查一个API,如果验证了登录名/密码,并检索有关用户填充我的数据库的一些信息(所以当我在我的登录页面时,我的用户表中实际上没有用户。

我正在使用此示例https://github.com/gonzalo123/silexSecurity,我已经像这样实现了它: - UserProvider

class UserProvider implements UserProviderInterface,ServiceProviderInterface{

private $users = array();

public function register(Application $app) {

   $app['users.security'] =  $app->share(function ($app) {
        return $this;
    });
}

public function boot(Application $app) {


}

 public function addUser(Application $app,$login, $pwd, $id_prvi,     $email, $job, $firstname, $lastname) {
    try{
    $app->db('mydb')->insert('users', array('idprvi' => $id_prvi, 'mail' => $email, 'username' => $login, 'password' => $pwd, 'job' => $job, 'firstname' => $firstname, 'lastname' => $lastname ));
    }catch(\Exception $e){ 
        return $e->getMessage();
    }
}
public function getUsers(Application $app){

    $users_db = $app->db('mydb')->fetchAll('SELECT username, password FROM users');

    foreach( $users_db as $user)
    {
        $this->users[$user['username']] = array(array('ROLE_USER'), $user['password']);
    }
    return $this->users;
}


public function ifUsersInDB($login){
   return array_key_exists($login,$this->users);
}

public function loadUserByUsername($username)
{
    if (!isset($this->users[$username])) {
        throw new UsernameNotFoundException(sprintf('"%s" does not exist.', $username));
    }
    return new User($username, $this->users[$username][1], $this->users[$username][0], true, true, true, true);
}
public function refreshUser(UserInterface $user)
{
    if (!$user instanceof User) {
        throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
    }
    return $this->loadUserByUsername($user->getUsername());
}
public function supportsClass($class)
{
    return $class === 'Symfony\Component\Security\Core\User\User';
}

}
  • 我的配置

     ...
     $app->register(new SecurityServiceProvider());
     $app->register(new SessionServiceProvider());
     $app->register(new UserProvider());
    
     $app['security.firewalls'] = array(
    'login' => array(
        'pattern' => '^/login(/|_check_api)?$',
    ),
    'secured' => array(
        'pattern' => '^.*$',
        'form' => array(
            'login_path' => '/login',
            'check_path' =>'/login_check',
            'default_target_path' => '/',
            'always_use_default_target_path' => true
        ),
        'logout' => array(
            'logout_path' => '/logout',
            'invalidate_session' => false
        ),
        'users' => $app['users.security']->getUsers($app)
    ),
    );
    
     $app['security.access_rules'] = array(
    array('^.*$', 'ROLE_USER'),
     );
        $app->on(AuthenticationEvents::AUTHENTICATION_FAILURE, function (AuthenticationEvent $event) {
     });
       $app->on(AuthenticationEvents::AUTHENTICATION_SUCCESS, function (AuthenticationEvent $event) {
     });
      $app->on(SecurityEvents::INTERACTIVE_LOGIN, function (InteractiveLoginEvent $event) {
      });
      $app->on(SecurityEvents::SWITCH_USER, function (SwitchUserEvent $event) {
        });
    
  • 形式

      <div id="form_user_login" >
        <div >
            <form action="{{ path('check_api') }}" method="post">
                <span class="red-text">{{ form_message | raw}}</span>
                <div class="col s4">
                    <div class="row">
                        <div class="input-field col s12">
                            <input type="text" name="_username" value="{{ last_username }}"  class = "validate" />
                        </div>
                    </div>
                    <div class="row">
                        <div class="input-field col s12">
                            <input type="password" name="_password" value="" class = "validate" />
                        </div>
                    </div>
                    <input type="submit" value="S'inscrire"/>
                </div>
            </form>
        </div>
    </div>
    

我想在调用login_check之前使用以下函数:

public function userAPICheck(Application $app, Request $request)
    {
        $message = "";
         $password =$request->get('_password');
         $login = "";
        try {
            $login = $request->get('_username');
            $api_password = $app['utils']->password($password);

            $api_response = $app['utils']->getKeyAccessUser($login, $api_password);
            $password = $app['security.encoder.digest']->encodePassword($password, '');
            dump($api_response);
            if ($api_response->return > 0) {dump(array('ici',$api_response));
                $message = "Erreur";
                $userToken->setAuthenticated(false);
            } else {

                if (!$this->ifUsersInDB($login)) {

                    $this->addUser($app,$login, $password, $api_response->uid, $api_response->email, $api_response->fonction, $api_response->prenom, $api_response->nom);
                 }

            }
        } catch (\Exception $e) {
            $message = $e->getMessage();
            dump($message);
        }
    }

是否可以这样做,还是必须使用完全其他的方法?

0 个答案:

没有答案