Regaez / grav-plugin-api

A REST API plugin for GravCMS
MIT License
27 stars 6 forks source link

feat: authentication using Session #78

Closed Regaez closed 4 years ago

Regaez commented 4 years ago

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

Regaez commented 4 years ago

@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 https://github.com/Regaez/grav-plugin-api/issues/68), so if it doesn't work it can be investigated as part of that issue.

masetto commented 4 years ago

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

Regaez commented 4 years ago

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