简体   繁体   中英

How to setup access control for the user in symfony?

I have a users table where roles field contains ["ROLE_SUPERUSER"]

Now I have two Urls:

  • localhost:8000/api/en/login
  • localhost:8000/api/en/test

When the user successfully logins, it generate a cookie. How can set the access control to the second URL where if the cookie is not set then this URL is not allowed.

I have added following lines to the security.yaml file

access_control:
 - { path: ^/api/{locale}, roles: IS_AUTHENTICATED_ANONYMOUSLY }
 - { path: ^/api/{locale}, roles: ROLE_SUPERUSER}

But this didn't work.

Any help?

In access_control first matching setting is taken. Because your patterns both match, all users will be IS_AUTHENTICATED_ANONYMOUSLY . You have to use seperate paths/patterns for your firewall to authorize with diffrent roles:

access_control:
 - { path: ^/api/{locale}/secured, roles: ROLE_SUPERUSER}
 - { path: ^/api/{locale}, roles: IS_AUTHENTICATED_ANONYMOUSLY }

You can find more info in the docs: Symfony - How to restrict Firewalls to a Request

The firewall will take the first route that matches and apply the restriction.

One doesn't want to apply some firewall restrictions for login path, so it can be excluded from the list.

I'm not 100% sure if {locale} in firewall will work, unlike in the route description. However, you can use RegEx to define a rule on ^/api/<anything>/test :

access_control:
 - { path: ^/api/.*?/test, roles: ROLE_SUPERUSER }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM