在埃德温给我指明了正确的方向之后,我成功地让这个工作成功了。事实上,加密并不是唯一的问题。
这些变化主要涉及注册控制器,其中修改了密码加密代码。
我还更改了现在基于的表单验证器this http://symfony.com/doc/current/security/guard_authentication.html
因为我的问题所指出的先前基础已经过时了。
最后,Symfony 不太喜欢 Ajax,因此 Ajax URL 进行了调整以适用于开发环境。
这是整个代码:
安全.yml
security:
encoders:
UsedBundle\Entity\User:
algorithm: bcrypt
providers:
db_provider:
entity:
class: UsedBundle:User
property: email
manager_name: used
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: ~
provider: db_provider
form_login:
login_path: /
username_parameter: _email
check_path: /login_check
guard:
authenticators:
- app.form_login_authenticator
logout:
path: /logout
target: /
access_control:
- { path: ^/admin, roles: ROLE_ADMIN }
- { path: ^/, roles: IS_AUTHENTICATED_ANONYMOUSLY }
注册控制器的变化:
if ($form->isSubmitted() && $form->isValid()) {
$this->formData = $request->request->get($form->getName('user'));
$this->plainPassword = $this->formData['plainPassword']['first'];
$password = $this->get('security.password_encoder')
->encodePassword($user, $this->plainPassword );
.....
新的验证器:
namespace UsedBundle\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\Security;
class FormLoginAuthenticator extends AbstractGuardAuthenticator
{
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function getCredentials(Request $request)
{
if ($request->getPathInfo() != '/login_check') {
return;
}
$email = $request->request->get('_email');
$request->getSession()->set(Security::LAST_USERNAME, $email);
$password = $request->request->get('_password');
return array(
'email' => $email,
'password' => $password
);
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$email = $credentials['email'];
return $this->user = $this->container
->get('doctrine')
->getRepository('UsedBundle:User', 'used')
->findOneByemail( $email );
}
public function checkCredentials($credentials, UserInterface $user)
{
$plainPassword = $credentials['password'];
$encoder = $this->container->get('security.password_encoder');
if (!$encoder->isPasswordValid($user, $plainPassword)){
throw new BadCredentialsException();
}else{
return true;
}
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
$session=$request->getSession();
$session->set('seller_id', $token->getUser()->getId());
$session->set('email', $token->getUser()->getEmail());
return new JsonResponse(
array(
'userId' => $token->getUser()->getId(),
'message' => $this->credentials,
'statut' => 'ok',
'roles' => $token->getUser()->getRoles(),
'email' => $token->getUser()->getEmail(),
)
);
// for non-AJAX requests, return the normal redirect
//return parent::onAuthenticationSuccess($request, $token, $providerKey);
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$data = array(
'message' => strtr($exception->getMessageKey(), $exception->getMessageData())
// or to translate this message
// $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
);
return new JsonResponse($data, Response::HTTP_FORBIDDEN);
}
/**
* Called when authentication is needed, but it's not sent
*/
public function start(Request $request, AuthenticationException $authException = null)
{
$data = array(
'message' => 'Authentication Required'
);
return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
}
public function supportsRememberMe()
{
return false;
}
}
登录控制器:
namespace UsedBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class LoginController extends Controller
{
/**
* @Route("/login", name="login")
*/
public function loginAction(Request $request)
{
$helper = $this->get('security.authentication_utils');
return $this->render('common/login.html.twig', array(
// last username entered by the user (if any)
'last_username' => $helper->getLastUsername(),
// last authentication error (if any)
'error' => $helper->getLastAuthenticationError(),
));
}
/**
* @Route("/login_check", name="security_login_check")
*/
public function loginCheckAction()
{
// will never be executed
}
}
这就是开发中 Ajax url 的样子:]
$.ajax({
url: "/app_dev.php/login_check",
type: "POST",
dataType: "json",
data: str,
success: function(data) {
.....