我的security.yml文件中有两个防火墙:
security:
encoders:
FOS\UserBundle\Model\UserInterface: bcrypt
providers:
fos_userbundle:
id: fos_user.user_provider.username_email
firewalls:
login:
pattern: ^/api/v1/auth$
stateless: true
anonymous: true
provider: fos_userbundle
form_login:
check_path: /api/v1/auth
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
require_previous_session: false
api:
pattern: ^/api/v1
stateless: true
provider: fos_userbundle
guard:
authenticators:
- lexik_jwt_authentication.jwt_token_authenticator
以及AuthController中的两条路线:
/**
* @param ParamFetcherInterface $paramFetcher
*
* @Rest\Post("/auth")
* @Rest\RequestParam(name="email", strict=true)
* @Rest\RequestParam(name="password", strict=true)
*
* @return array
*/
public function postTokenAuthAction (ParamFetcherInterface $paramFetcher)
{
if($user = $this->getUser()) {
return $user->getRoles();
}
$email = $paramFetcher->get('email');
$password = $paramFetcher->get('password');
/** @var User|null $user */
$user = $this->getDoctrine()->getRepository('AppBundle:User')->findOneByEmail($email);
if(!$user || !$this->get('security.password_encoder')->isPasswordValid($user, $password)) {
throw new HttpException(403, $this->get('translator')->trans('auth.error'));
}
$token = $this->get('lexik_jwt_authentication.encoder')->encode([
'email' => $user->getEmail()
]);
return ['access_token' => $token];
}
/**
* @param ParamFetcherInterface $paramFetcher
*
* @Rest\Post("/auth/check")
*
* @return array
*/
public function postCheckLoginAction (ParamFetcherInterface $paramFetcher)
{
/** @var User $user */
$user = $this->getUser();
if (!$user) {
throw $this->createAccessDeniedException();
}
return $user->getRoles();
}
/api/v1/auth
我使用 POST参数发送 POST 请求email=&password=
以获取 access_token。但我收到 401 错误“凭据错误”。
好的。接下来,我将防火墙中的参数更改为pattern
和,它工作正常。现在我可以通过电子邮件和密码登录并获取 access_token。 login
^/api/v1/auth
form_login.check_path
/api/v1/auth/check
但是 route/api/v1/auth/check
现在返回Bad credentials。它试图在这条路线中通过电子邮件和密码授权我,但我希望它尝试通过Authorization标头授权。
为什么它工作不正常?
最终,我想要发送email
和password
获取,然后发送到并/api/v1/auth
获取用户角色。access token
access_token
/api/v1/auth/check