To implement the Proof Key for Code Exchange (PKCE) flow for OAuth 2.0 in a Figma plugin, you can follow these general steps:
Steps to Implement PKCE in a Figma Plugin
1. Generate a code verifier: Create a cryptographically random string using a library like `crypto-js` or `pkce-challenge`. This will be the `code_verifier`.
2. Generate a code challenge: Create a SHA-256 hash of the `code_verifier` and then base64url encode it. This will be the `code_challenge`.
3. Start the OAuth flow: In your plugin, open a new browser window (using `window.open()`) and redirect the user to the OAuth authorization URL, passing the following parameters:
- `client_id`: Your application's client ID
- `response_type`: Set this to `code`
- `redirect_uri`: The callback URL on your server
- `scope`: The scopes you're requesting access to
- `code_challenge`: The `code_challenge` you generated in step 2
- `code_challenge_method`: Set this to `S256`
4. Handle the OAuth callback: When the user is redirected back to your callback URL, your server should:
- Verify that the `state` parameter matches the one you sent earlier (to prevent CSRF attacks)
- Exchange the authorization code for an access token using the `code_verifier` you generated in step 1:
- Make a POST request to the token endpoint, passing the following parameters:
- `client_id`: Your application's client ID
- `code`: The authorization code received in the callback
- `code_verifier`: The `code_verifier` you generated in step 1
- `grant_type`: Set this to `authorization_code`
- `redirect_uri`: The same callback URL as before
5. Store the access token: Once you've received the access token, store it securely in your plugin's storage (using `figma.clientStorage`) so you can use it for subsequent API requests.
The key benefits of using PKCE are:
- It eliminates the need to store a client secret, which is important for Figma plugins that run in a sandboxed environment.
- It provides an additional layer of security by binding the authorization code to the client application.
The Figma documentation provides more details on the PKCE flow for Figma plugins: OAuth with Plugins | Plugin API
Citations:[1] https://evilmartians.com/chronicles/how-to-make-next-level-figma-plugins-auth-routing-storage-and-more
[2] https://www.figma.com/plugin-docs/oauth-with-plugins/
[3] https://github.com/didoo/figma-api
[4] https://forum.figma.com/t/authentication-in-figma-plugin-using-oauth/39079
[5] https://forum.figma.com/t/oauth-with-figma-itself/22522