Silex 및 보안 서비스를 사용하는 데 약간의 문제가 있습니다.로그인 성공 후 Silex가 직접 응답하지 않습니다.
사용자가 로그인 양식에 데이터를 올바르게 입력해도 앱 URL로 리디렉션되지 않습니다. 그는 동일한 페이지에 남아 있고 디버깅은 로그인 폼 페이지에서 보안 공급자가 인증되었음을 나타내는 어떠한 것도 가지지 않습니다. 하지만 '성공적인 로그인'이후에 브라우저에 URL을 직접 입력하면 인증되었으므로 액세스 할 수 있습니다. 이 과정처럼 뭔가 :
홈 페이지 -> 로그인 확인 (OK 로그인) -> (인증되지 않은) 홈 페이지 - (인증)>/응용 프로그램
가 나는 경우/응용 프로그램에 직접 리디렉션을하고 싶습니다 로그인이 정상적으로 작동하고 내 홈 페이지에서 성공적인 로그인 후에도 보안 공급자가 계속해서 인증을받지 못했다고 말하는 이유를 이해할 수 있습니다.
내가 따라와 코드를 쓰고 있어요 :
index.php를
<?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints as Assert;
require_once __DIR__.'/../vendor/autoload.php';
$app = new Silex\Application();
/**
* App Registrations & Debug Setting
*/
$app
->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__.'/../views'))
->register(new Silex\Provider\UrlGeneratorServiceProvider())
->register(new Silex\Provider\SessionServiceProvider())
->register(new Silex\Provider\FormServiceProvider())
->register(new Silex\Provider\ValidatorServiceProvider())
->register(new Silex\Provider\TranslationServiceProvider(), array(
'translator.messages' => array(),
))
->register(new Silex\Provider\DoctrineServiceProvider(), array(
'db.options' => array(
'driver' => 'pdo_mysql',
'dbname' => 'pomodesk',
'host' => 'localhost',
'user' => 'root',
'password' => 'root'
)
))
->register(new Silex\Provider\SecurityServiceProvider(), array(
'security.firewalls' => array(
'app' => array(
'pattern' => '^/app',
'http' => true,
'form' => array('login_path' => '/', 'check_path' => '/app/login_check'),
'logout' => array('logout_path' => '/app/logout'),
'anonymous' => false,
'users' => $app->share(function() use ($app) {
return new Pomodesk\Provider\UserProvider($app['db']);
})
),
),
'security.access_rules' => array(
array('^/app', 'ROLE_USER')
)
));
$app['debug'] = true;
/**
* App Routes
*/
$app->get('/', function(Request $request) use ($app) {
$form = $app['form.factory']
->createBuilder('form')
->add('name', 'text')
->add('email', 'text')
->add('password', 'password')
->getForm();
if ('POST' == $request->getMethod()) {
$form->bind($request);
$data = $form->getData();
$constraint = new Assert\Collection(array(
'name' => array(new Assert\Length(array('min' => 5)), new Assert\NotBlank()),
'email' => new Assert\Email(),
'password' => array(new Assert\Length(array('min' => 6)), new Assert\NotBlank())
));
$errors = $app['validator']->validateValue($data, $constraint);
$userProvider = new Pomodesk\Provider\UserProvider($app['db']);
try {
$duplicated = $userProvider->loadUserByUsername($data['email']);
} catch (Exception $e) {
$duplicated = false;
}
if ($form->isValid() && count($errors) < 1 && !$duplicated) {
$user = new \Symfony\Component\Security\Core\User\User($data['email'], '', array('ROLE_USER'));
$encoder = $app['security.encoder_factory']->getEncoder($user);
$insertion = $app['db']->insert(
'user',
array(
'email' => $data['email'],
'name' => $data['name'],
'password' => $encoder->encodePassword($data['password'], $user->getSalt()),
'roles' => 'ROLE_USER'
)
);
return $app['twig']->render('home.html.twig', array(
'username' => $data['email'],
'signup' => true
));
}
return $app['twig']->render('home.html.twig', array(
'username' => $data['email'],
'signup' => true
));
}
return $app['twig']->render('home.html.twig', array(
'error' => $app['security.last_error']($request),
'last_username' => $app['session']->get('_security.last_username'),
'form' => $form->createView()
));
})
->method('GET|POST')
->bind('home');
$app->get('/app', function() use ($app) {
$app['app_js'] = $app['twig']->render('script.js.twig');
$data = array();
return $app['twig']->render('app.html.twig', $data);
})
->bind('app_home');
$app->run();
UserProvider.php
<?php
namespace Pomodesk\Provider;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Doctrine\DBAL\Connection;
class UserProvider implements UserProviderInterface
{
private $conn;
public function __construct(Connection $conn)
{
$this->conn = $conn;
}
public function loadUserByUsername($username)
{
$stmt = $this->conn->executeQuery('SELECT * FROM user WHERE email = ?', array(strtolower($username)));
if (!$user = $stmt->fetch()) {
throw new UsernameNotFoundException(sprintf('Email "%s" does not exist.', $username));
}
return new User($user['email'], $user['password'], explode(',', $user['roles']), 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';
}
}
감사합니다 많이!
->register(new Silex\Provider\SecurityServiceProvider(), array(
'security.firewalls' => array(
'app' => array(
'pattern' => '^/',
'http' => true,
'form' => array('login_path' => '/', 'check_path' => '/app/login_check'),
'logout' => array('logout_path' => '/app/logout'),
'anonymous' => true,
'users' => $app->share(function() use ($app) {
return new Pomodesk\Provider\UserProvider($app['db']);
})
),
),
'security.access_rules' => array(
array('^/app', 'ROLE_USER')
)
));
방화벽에서 익명 사용자를 허용하고, 바로 액세스 규칙과/응용 프로그램 경로를 보호 :
고맙습니다. – joaobarbosa
안녕하세요, 로그인에 github가 있습니까? 또한 로그인 프로세스가 필요하므로 내 로컬에서 시도 할 수 있도록 작업 복사본을 가질 수 있습니까? – knives22