Proof Key for Code Exchange (PKCE) is a specification built on OAuth 2.0 that was introduced to create a more secure login flow. We've adapted PKCE to work on magic link flows as well - increasing their security while preserving their usability.
You can read more about PKCE's role in OAuth in our PKCE OAuth guide.
PKCE makes magic links more secure by cryptographically validating that the login flow starts and ends on the same device. In a standard magic link flow, the link contains a one time code in a redirect URL. The user clicks on the link, the app receives the code, and the code is exchanged for a session to log in the user. This setup means that an attacker would be able to impersonate a user if the attacker gained access to the one-time code. Codes in a URL can be leaked in many different ways - either through improper logging, HTTP Referrer headers, or even through another exploit like XSS.
PKCE improves on this by introducing a one-time secret for each authorization flow. This secret, called a code_verifier, is generated and stored by the app on the user's device. The verifier then is hashed to produce a code_challenge. This challenge is passed along with the user's email to Stytch when the user is asked to verify their identity.
Stytch sends the user an email containing a magic link. When the user clicks on that link, the user is redirected back to the app with a secure code. Next, the app submits the code along with the original code_verifier. Stytch hashes the submitted code_verifier and validates that it matches the code_challenge passed as a query parameter earlier. This check ensures that the token has not been leaked, and that it is being handled by the same user that was seen at the start of the flow.
This guide will show you how to add PKCE support to your Stytch magic link integration for added security. A PKCE integrations is required for applications that use native callback URLs, for example appname://some/callback on mobile. Stytch's support for PKCE differs slightly from the original specification - for example we do not permit plain verifiers to be used - but the original idea of strengthening app security with a unique secret on every request remains the same.
If you get stuck while working through this guide, feel free to ask questions in our forum, via support@stytch.com, or in our Slack community.