Authorization Code Grant
Last updated
Last updated
Some API providers implement the OAuth 2 Authorization Code Flow for authentication. Implementing this grant type every time you create a new API integration can be tedious and time-consuming. Saloon offers a simple, extendable OAuth2 trait to help you get up and running quickly.
This section of the documentation assumes that you are familiar with OAuth2 and specifically the Authorization Code Grant. If you are not familiar with how this grant type works,
Saloon has provided methods for the full Authorization Code grant.
Let’s start with preparing our connector to support the Authorization Code Flow. All we have to do is add the AuthorizationCodeGrant
trait to our connector.
After you have added the trait, you will need to tell Saloon how to authenticate with your API. First, extend the defaultOauthConfig
method and use the methods to define your client ID, secret and redirect URI. Saloon also has sensible defaults set for the authorization and token endpoints, but you may customize them if you need to. For example, Spotify has a different base URL than the connector's base URL, so we have overwritten it in this example.
You can also provide default scopes and even provide a callback to modify the OAuth2 requests being sent.
Sometimes, you may have a different OAuth2 client ID and secret for each user of your application. If your OAuth2 config is dependent on a per-user/tenant basis, it's recommended that you pass in the credentials as constructor arguments of your connector and then set the oauthConfig
inside the constructor.
In the following example, I will pass in the $clientId
and the $clientSecret
as constructor arguments and overwrite the OAuth2 config.
Now we have setup our connector to support the authorization code grant, we are ready to start the OAuth2 process. Usually, the first stage is to generate a URL to redirect our application users to. To generate an authorization URL, you can use the getAuthorizationUrl
method on the connector.
You can also pass in scopes which will be merged with the default scopes if you provided them in the OAuth config. Saloon will separate scopes with spaces but if your API integration requires scopes to be separated any other way, you can specify this with the scopeSeparator
argument.
You can also provide additional query parameters if you need to with the additionalQueryParameters
argument. This should be a key-value array where the key is the query parameter name and the value is the value of the query parameter.
To help prevent CSRF attacks or send additional data during authentication, you can pass an additional unique string in your authorization URL that the API's OAuth2 server will send back to you after your user has approved or denied access to your OAuth2 app.
If you do not provide your own state, Saloon will automatically generate a unique, 32-character string. Once you have generated the authorization URL, you can then use the getState
method on your connector to get the state back. You should store this string in your application's session or cache to be verified later.
If you stored the state that was generated during creating an authorization URL, you should pass this expected state alongside the state sent back by the API provider's OAuth2 server. This will be used to verify the state provided back by the application is valid. If the state does not match the expected state, Saloon will throw an exception.
You will likely need to store the authenticator securely so you can use it for future requests. You may serialize and unserialize the authenticator class using the helper methods below, then you can store the string wherever you like, usually encrypted in the database if it's against a user. Then, you can retrieve this authenticator and use it to authenticate your connector.
The authenticator returned by Saloon when using the getAccessToken
or refreshAccessToken
methods will contain the Access Token, Refresh Token and Expiry Date that was returned by the OAuth2 server. You can access these properties with the following methods. You can also check if the authenticator has expired, which will come in handy when refreshing access tokens.
When retrieving your authenticator out of storage, you should always check if the access token has expired and if it needs refreshing. If the authenticator's access token has expired, you can call the refreshAccessToken
method which will create a fresh authenticator.
In this example, $user
is the user of my application and I have written methods to get and store the authenticators.
Sometimes the API provider you are authenticating with may require additional information to be used in the authenticator. You can customise how the authenticator will be created by extending the createAccessTokenAuthenticator
method on your connector.
Sometimes the API provider you are authenticating with may have a different way that they respond with their tokens. If you need to customise the way Saloon creates the authenticator you can extend the createOAuthAuthenticatorFromResponse
method.
Sometimes you might integrate with an API that requires additional query parameters or headers to be sent with the OAuth2 flow. You may use the requestModifier
property on the methods or use the setRequestModifier
method within the OAuthConfig
to add a callable that is invoked before a request is sent.
There are situations where Saloon's own request classes for getting the access token, refreshing the access token or getting the user might not suit the API you are integrating with. For example, if an API uses JSON encoding instead of form encoding. You may use the following methods on your connector to overwrite the instantiation process of the request classes.
If you prefer, you may request Saloon to return a Saloon\Http\Resonse
instance instead of a AccessTokenAuthenticator
when creating or refreshing access tokens. To use responses, just provide the returnResponse
argument when creating or refreshing access tokens.
If you would like to see an example integration using the OAuth2 methods mentioned above, you can see the following Laravel application.
After the user has approved your application, the API provider will redirect you back to your application with an authorization code and state. This data usually sent in the form of query parameters should be passed into your getAccessToken
method on your connector. If successful, the method will return an AccessTokenAuthenticator
. The access token, refresh token and expiry are wrapped up in a class that can be used to authenticate your connector/requests. It acts like a DTO that can be easily serialized and transported around your application.