What is PKCE in OAuth 2.0? ??
PKCE stands for Proof Key for Code Exchange. Have you ever had the thought of "Wonder what would happen if someone else took my authorization code and exchanged it for access & refresh tokens? Would it actually work?". Well here's where PKCE comes in place.
PKCE prevents authorization code interception attacks by adding an extra step when exchanging the authorization code for an access token. Let's get a quick refresh on the Authorization Code Flow in OAuth 2.0
This is a generic flow, In MVC applications sending over the authorization code along with the client secret is generally safe because backend servers can securely store client secrets.
However in mobile apps, frontend apps you can't securely store secrets because javascript can be easily manipulated. So allegedly if anyone has the authorization code he can send it over to google and get an access token (you wish ??) Here's where PKCE comes in place
How PKCE works
1) Before starting the OAuth flow, the client generates:
2) The client sends the authorization request to the authorization server with:
Sending the hashed value and the method so we can convert & compare anything sent to us later with these values
3) Authorization Server Returns Authorization Code
If the user approves, the authorization server returns an authorization code.
4) The client sends another request to exchange the authorization code for an access token, but this time it includes:
5) Server Validates Code Verifier
The authorization server re-computes the hash from the code verifier and checks if it matches the code challenge from step 2.
领英推荐
This can safely prevent anyone with the authorization code only to retrieve an access token. He would need the code verifier which is generated by the frontend during the lifecycle of the authorization flow
So to sum up everything
If you have a backend server it would be more recommended to generate the code verifier there and just send the code challenge from the frontend as anything hashed can't be returned to its original state.
Adjusting the above if u have a backend server
1?? Frontend requests authentication:
2?? Frontend redirects user to the authorization server:
3?? Frontend sends the authorization code to the backend:
4?? Backend exchanges the code for an access token:
5?? Backend sends access token to frontend (if needed):
Hopefully you got something out of this little article! thanks and till the next one!