OAuth2 Resources

Last updated 6 months ago

Not yet officially released or documented. What is in this documentation article may not work as intended.

Getting Started

In order to get started we just need to put our endpoint behind OAuth2 authentication. We can do this simply by importing the authentication class from the entry package and putting it into our resource:

from entry.api.auth.OAuth2 import OAuth2
class UserResource(Resource, JsonSerialize, OAuth2):
model = User

Great! Now we have full OAuth2 support.

Routes

We can simply add all the routes we need for this endpoint by importing and adding them to the routes list:

from entry.api.controllers import OAuth2Controller
ROUTES = [
...
OAuth2Controller.routes()
...
]

CSRF Middleware

Some of these routes are POST routes. Because they are externally facing, they should not be under CSRF protection. If you are using these routes internally then it might be worth it to keep the CSRF protection on and just pass the CSRF token you receive on that page load.

You can turn off CSRF protection on specific routes by adding them to your exempt attribute on your CSRFMiddleware:

class CsrfMiddleware:
exempt = [
'/oauth/token',
'/oauth2/authorize',
'/oauth2/refresh'
]
...

Great!

Publishing Controllers

Although this package can handle most use cases, you will likely want to tweak how tokens are authenticated or how long tokens are good for. The best way to do this will be to publish the controller or authentication classes to your application so you can use them yourself.

Publishing simply moves them from the package and into your application.

You can publish a controller by running:

$ craft entry:publish --controller OAuth2Controller

or publish an authentication class:

$ craft entry:publish --auth OAuth2

You can also specify a location:

$ craft entry:publish --controller OAuth2Controller --path app/api/entry

Here are a list of classes that you can publish:

Controllers

Authentication

OAuthController

JWTGrantController

Generating Tokens

Now that we have new routes, let's explain what they are:

get
Authenticating Your Application

http://localhost:8000
/oauth2/token?client_id=1234-xx&redirect_uri=http://example.com
This is not an external endpoint. Redirect to the user from your application to this endpoint so they can authenticate your application.
Request
Response
Query Parameters
scope
optional
string
Any requesting scopes found in the database
state
optional
string
A random string that will be sent back when the user authenticates
client_id
required
string
The client_id of the application you are authenticating
redirect_uri
required
string
The URI which will be redirected when the user authenticates. This should be match the URI if your application.
200: OK