RESTFul OAuth with FOSOAuthServer / FOSRest & FOSU

2019-07-15 11:02发布

问题:

I'm having difficulties to fully understand the concept of the client creation explained here. I followed the post to set up the OAuthBundle, and tried to make the changes needed to comply with FOSUser. Though I'm not sure it's perfect.

My situation

  • My Website is a RESTFul API, which return json or xml only. My frontend will be in AngularJS
  • I combined FOSUser, FOSRest and FOSOAuth, it's possible I'm having errors in the configuration.

The Problem

I finished setting up the first part of the article up to the doctrine:schema:update command. Now I'm supposed to create a client.

How can I set the security for parts of the ^/api for differents ROLES ?

example:

  • Anonymous users can access POST /api/users but not GET /api/users.
  • Only users with ROLE_ADMIN can access DELETE /api/users/{id}

For testing I'm using Postman (that support OAuth1 & 2, along with other means of auth).

回答1:

Using expressions in security.yml

In order to secure certain routes by a conditional combination of (request)-method AND (user)-role ...

... you can make use of Expressions in your security.yml.

More information can be found in the documentation chapter Securing by an Expression.

Example

Only users with role ROLE_ADMIN shall be allowed to access /api/users/{id} using a DELETE request:

# app/config/security.yml
security:
    # ...
    access_control:
        - path: "^/api/users/\d+$"
          allow_if: "'DELETE' == request.getMethod() and has_role('ROLE_ADMIN')"

Regex explanation

  • ^ begins with
  • \d+ one or more digits (= user id)
  • $ string end