Handle the Authorization Code

In the previous steps we have set up an oauth client and learned how users can scan a QR code to grant access to their bunq account.

In this chapter we'll learn how to complete the oauth flow and handle the authorization code.

Once the user authorizes your app, bunq will redirect them to your registered redirect_uri with a code and state parameter this may look like this:

https://myapp.com/oauth/callback?code=AUTH_CODE&state=xyz789

It's your responsibility to have a endpoint on your server that can catch that callback and retrieve the code and state.

The state parameter is a recommended security feature in the OAuth 2.0 flow. It serves two key purposes:

  1. Prevents CSRF Attacks When initiating the OAuth authorization request, you should generate a unique and unpredictable state value and store it temporarily (e.g. in a session, database, or memory store). When the user is redirected back to your redirect_uri, you must verify that the returned state matches what you originally sent.

  2. Preserves Application Context You can also use state to carry context from your app, such as the ID of the user initiating the flow or the page they started from. This allows you to restore state after the OAuth flow completes.

The authorization code is a short-lived, one-time-use credential returned by bunq after a user grants your app permission. It serves as a temporary token that can be securely exchanged for long-term credentials.

Exchanging the Authorization Code for an Access Token

Once bunq redirects the user to your app with a code, you can exchange it for an access token by making a POST request to:

thttps://oauth.bunq.com/token

Required Parameters

  • grant_type: must be authorization_code

  • code: the code you received in the redirect

  • redirect_uri: must match the one you registered

  • client_id: your OAuth client ID

  • client_secret: your OAuth client secret


Example cURL Request

curl -X POST https://oauth.bunq.com/token \
  -d grant_type=authorization_code \
  -d code=AUTH_CODE \
  -d redirect_uri=https://myapp.com/oauth/callback \
  -d client_id=YOUR_CLIENT_ID \
  -d client_secret=YOUR_CLIENT_SECRET

Replace:

  • AUTH_CODE with the code you received from bunq

  • YOUR_CLIENT_ID with your actual client ID

  • YOUR_CLIENT_SECRET with your client secret

  • https://myapp.com/oauth/callback with your registered redirect URI


Example Successful Response

{"access_token":"8ac6eb1d3a1a36f0bb16afe2b776d5b32f88393da19c06657cf05167da19aa16","token_type":"bearer","state":"hMtbxh3o11-pMiN5E8KOgw"}

It's a good idea to store this access_token in your database and associate it with your end-user. We cannot use the access token to make API calls to bunq directly. Instead we use the Access Token to obtain a session token that we then can use on behalf of the user.


Last updated

Was this helpful?