Proof Key for Code Exchange
PKCE (Proof Key for Code Exchange by OAuth Public Clients)
OAuth 2.0 is the preferred mechanism for authorizing native mobile applications to their corresponding API endpoints. In order to be authorized, the native application attaches an OAuth access token to its API calls. Upon receiving a call, the API extracts the token, validates it (checks issuer, lifetime, associated authorizations, etc) and then determines whether the request should be allowed or denied.
Of course, before the native application can use an access token on an API call, it must necessarily have first been issued that token. OAuth defines how the native application, with a user’s active involvement, interacts with an Authorization Server (AS) in order to obtain a set of tokens that represent that user and their permissions. The best practice for native applications leverages a version of OAuth called the ‘authorization code grant type’ – which in this context consists of the following steps
- Upon installation, the native application registers itself with the mobile OS as the handler for URLs in a particular scheme, e.g. those starting with ‘com.example.mobileapp://’ as opposed to ‘http://’.
- After installation, the native application invites the user to authenticate.
- The native application launches the device system browser and loads a page at the appropriate AS.
- In that browser window, the AS
authenticates the user. Because authentication happens in a browser, the AS has flexibility in the how & where the actual user authentication occurs, i.e., it could be through federated SSO or could leverage 2 Factor Authentication etc. There are advantages to using the system browser and not an embedded browser – notably that a) any credentials presented in the browser window are not visible by the application b) any session established in the browser for one native application can be used for a second, enabling a SSO experience may obtain the user’s consent for the operations for which the native application is requesting permission
- If step 4 is successful, the AS builds a URL in the scheme belonging to the native application and adds an authorization code to the end of the URL, e.g. ‘com.example.mobileapp://oauth?code=123456. The AS directs the user’s browser to redirect to this URL
The browser queries the mobile OS to determine how to handle this URL. The OS determines the appropriate handler, and passes the URL to the appropriate application
- The native application parses the URL and extracts the authorization code from the end
- The native application sends the authorization code back to the AS
- The AS validates the authorization code and returns to the native application an access token (plus potentially other tokens)
- The native application then stores that access token away in secure storage so it can be subsequently used on API calls.