如何解决Vue Js / Symfony / Api 平台身份验证通过会话错误 401
我观看了关于 api 平台和安全性的最新 symfony 演员表(第 2 章:API 平台安全性)我在后者的第 5 章(登录成功和会话)中被阻止。当我使用用户的凭据从我的 Vuejs 应用程序发送带有 axios 的 POST 请求时,API 确实向我发送了我的用户的 IRI。直到一切顺利,但是当我尝试向我的 API 发送 GET 请求以显示相关用户的信息时,它会返回 401 错误,因为是的,我已经设置了一个投票系统,因此只有数据的所有者它绘制访问它。所以我的用户没有登录,我在那里阻止了自己。
/**
* @Route("/api/login",name="api_login",methods={"POST"})
*/
public function login(IriConverterInterface $iriConverter)
{
if(!$this->isGranted('IS_AUTHENTICATED_FULLY')){
return $this->json([
'error' => 'Invalid login reuqest'
],400);
}
return $this->json([
'location' => $iriConverter->getIriFromItem($this->getUSer())
]);
}
这是我的 security.yaml :
security:
encoders:
App\Entity\User:
algorithm: auto
providers:
app_user_provider:
entity:
class: App\Entity\User
property: email
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: true
lazy: true
provider: app_user_provider
logout:
path: api_logout
stateless: false
json_login:
check_path: api_login
username_path: email
password_path: password
这是我的实体 User 和我的 user_Voter 的注释:
/**
* @ORM\Entity(repositoryClass=UserRepository::class)
* @UniqueEntity(fields={"email"},message="Email existant")
* @ApiResource(
* normalizationContext={"groups"={"user:read"}},* denormalizationContext={"groups"={"user:write"}},* collectionoperations={
* "GET",* "POST",* },* itemOperations={
* "GET"= {"security" = "is_granted('USER_VoteR',object)"},* "PATCH"= {"security" = "is_granted('USER_VoteR',* "DELETE"
* },* )
*/
public function Vote(TokenInterface $token,$subject,array $attributes)
{
if(!$subject instanceof User){
return self::ACCESS_ABSTAIN;
}
if(!in_array('USER_VoteR',$attributes)){
return self::ACCESS_ABSTAIN;
}
$user = $token->getUser();
if(!$user instanceof UserInterface){
return self::ACCESS_DENIED;
}
if($subject !== $user){
return self::ACCESS_DENIED;
}
return self::ACCESS_GRANTED;
}
PS:抱歉我从一月开始使用 symfony
解决方法
使用 lexik_jwt_authentication 生成 jwt 令牌。
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
api:
pattern: ^/api/v1/
stateless: true
anonymous: true
provider: app_user_provider
guard:
authenticators:
- lexik_jwt_authentication.jwt_token_authenticator
main:
anonymous: true
json_login:
check_path: /login
username_path: username
password_path: password
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。