Regaez/grav-plugin-api

feat: authentication using Session

Regaez opened this issue · 3 comments

At the moment, the AuthMiddleware only checks for basic authentication. However, if you want to use the API from within the context of your Grav site, i.e. making Ajax requests from your theme, or a plugin page, then it should be possible to use the session to authorise these.

When you log into a grav site (e.g. using the login plugin), the plugin adds the user to the session, which we can extract compare with the required roles.

Tasks

  • add the login plugin to the docker Grav instance
  • extend the AuthMiddleware:
    • check if a session contains a user
    • compare the roles of the user, allowing the request if they have the necessary roles.

@masetto I just merged this to master, so it's now possible to authorise API client side AJAX requests if you are logged into the Grav site.

This authorisation method will be preferred over Basic auth, so there is no need to provide the Authorization header with your client side request.

Note: the user must still have a relevant roles (e.g. api.super, or api.pages_edit, etc) in order to be able to use the API. If the user does not have one of the necessary roles, the request will return 401.

I only tested with the login plugin, so I don't know if this will work with other plugins such as oauth2 login, but it should, providing they also use Grav's Session class and add the user to it. There's an open issue to add authorisation via oauth anyway (see #68), so if it doesn't work it can be investigated as part of that issue.

@Regaez Great! I've already tried it and it works. Very useful. Thanks.

@masetto Awesome. Feel free to open any issues in the future if you encounter problems, or have ideas for features that could be added.