OAuth 2 Clients in Rust With the oauth2 Crate Step by Step
Implement the OAuth 2 authorization code flow with PKCE in Rust using the oauth2 crate: build the client, redirect, verify state, exchange the code and store tokens safely.

Signing users in with an identity provider, or calling another service's API on a user's behalf, means speaking OAuth 2. The protocol is not hard, but it is easy to get subtly wrong in ways that pass every happy-path test: a missing state check, a redirect that is followed when it should not be, a code that can be replayed. The oauth2 crate handles the wire format and gives you types that make the flow hard to misuse. This guide builds an authorization-code client with PKCE in Rust, tests it end to end against a small local stand-in for a provider, and then attacks it four ways: a normal login, a forged callback, a stolen authorization code and a code replay. The output of each is shown. Versions: rustc 1.99.0, oauth2 5.0.0, tokio 1.54, on an Apple M1 Max. The provider in the tests is a mock I wrote, not Google, GitHub or any real service, so the guide proves the client's behaviour and the protocol mechanics, and says nothing about the quirks of a particular provider.
The flow, in the order things happen
The authorization-code flow involves three parties: the user in a browser, your client (a web app or a command-line tool), and the provider's authorization server. In order:
- Your client builds an authorization URL and sends the user's browser to it. The URL names your
client_id, thescopeyou want, aredirect_urito come back to, a randomstateand a PKCEcode_challenge. - The user signs in at the provider and approves the request.
- The provider redirects the browser to your
redirect_uriwith two query parameters: a short-livedcodeand thestateyou sent. - Your client checks that the returned
stateequals the one it stored, then sends thecodeto the provider's token endpoint, together with the PKCEcode_verifier. - The provider checks the code and the verifier and returns an access token, usually with an expiry and a refresh token.
Two of those parameters exist purely for defence, and each blocks a specific attack. state defends the redirect in step 3: without it an attacker can send a victim a callback URL carrying the attacker's own code, and the victim's session is silently linked to the attacker's account. PKCE (Proof Key for Code Exchange, RFC 7636) defends step 4: the client invents a secret code_verifier and sends only its hash, the code_challenge, in step 1. Anyone who intercepts the code in step 3 cannot redeem it without the verifier, which never travelled through the browser. PKCE was designed for apps that cannot keep a client secret; the current OAuth 2.1 direction is to use it for every authorization-code client, confidential or not.
What PKCE actually computes
With the S256 method, the challenge is the URL-safe base64 of the SHA-256 of the verifier, with no padding. RFC 7636, appendix B, publishes a test vector, and it is worth checking a primitive against a published vector before relying on it. The first line the program prints is that check, computed with sha2 and base64:
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use sha2::{Digest, Sha256};
let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
println!("S256 vector: {}", URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())));S256 vector: E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cMThat is exactly the challenge the RFC lists for that verifier, which confirms the encoding (URL-safe alphabet, no padding) is what the provider will compute. The oauth2 crate does this for you in PkceCodeChallenge::new_random_sha256(); the check is here so the provider's side of the story is not a black box, and because the mock server uses the same arithmetic to verify.
Building the client
The crate's BasicClient is a typed builder. You supply the client id, then set the endpoints, and the type records which ones are set, so a client without a token URL cannot call exchange_code: the method does not exist on that type. That is the compiler enforcing configuration order, and it replaces a whole class of runtime "endpoint not configured" errors.
use oauth2::basic::BasicClient;
use oauth2::reqwest;
use oauth2::{
AuthUrl, ClientId, ClientSecret, CsrfToken, PkceCodeChallenge, RedirectUrl, Scope, TokenUrl,
};
let client = BasicClient::new(ClientId::new("demo-app".into()))
.set_client_secret(ClientSecret::new("demo-secret".into()))
.set_auth_uri(AuthUrl::new(format!("{base}/authorize"))?)
.set_token_uri(TokenUrl::new(format!("{base}/token"))?)
.set_redirect_uri(RedirectUrl::new("http://localhost:8080/callback".into())?);
// Redirects are off: following one from a token endpoint is an SSRF hole.
let http = reqwest::ClientBuilder::new()
.redirect(reqwest::redirect::Policy::none())
.build()?;Note that oauth2::reqwest is a re-export. The crate pins its own version of reqwest, and mixing in your own, newer reqwest as a separate dependency produces two incompatible Client types that fail to satisfy the crate's HTTP-client trait. Re-exporting avoids that, and I hit exactly this when my first Cargo.toml listed reqwest 0.13 beside a crate built on 0.12. The redirect policy deserves the comment it carries. A token endpoint that answers with a redirect is either misconfigured or hostile, and a client that follows it will send the authorization code, and the client secret, wherever the Location header points. The crate's documentation says to disable redirects, and the builder above does.
Step one: the authorization URL
The client creates a PKCE pair and a state token, then builds the URL. The verifier stays in your process; only the challenge goes out. This is the URL the library produced for a client of the same shape, against a placeholder provider, printed one parameter per line:
let (challenge, _verifier) = PkceCodeChallenge::new_random_sha256();
let (url, csrf) = client
.authorize_url(CsrfToken::new_random)
.add_scope(Scope::new("profile".into()))
.add_scope(Scope::new("email".into()))
.set_pkce_challenge(challenge)
.url();
for (k, v) in url.query_pairs() {
println!("{k:<22} {v}");
}response_type code
client_id demo-app
state Ib9v189xvJ4MNzQz1kD0vA
code_challenge rUyhW8l9fTAxPJiU3i8q1l_YlzCb89V43Cg-5CPlO7U
code_challenge_method S256
redirect_uri http://localhost:8080/callback
scope profile emailEvery parameter has a job. response_type=code selects the authorization-code flow. state is 22 characters of randomness, the crate's default for CsrfToken::new_random, and you must keep it, tied to this browser session, until the callback. code_challenge and code_challenge_method=S256 carry the PKCE hash. redirect_uri must match one registered with the provider exactly, character for character; providers that allow pattern matching or open redirects turn this into an account-takeover bug, so register the narrowest URL you can. scope is space-separated, and ask for the least you need, because a token with email only is worth less to a thief than one with every permission. Store the state and the verifier together, server side or in a signed, short-lived cookie, and delete them after one use.
Step two: the callback and the exchange
When the user comes back, the callback handler does two things in a fixed order: check the state, then exchange the code. The test program plays both the browser and the provider, so it can run the whole thing in one process. Its mock provider runs on an ephemeral local port and enforces three rules a real one does: the PKCE hash must match, a code works once, and the refresh token must be the one it issued. The client side of the callback is short:
if returned_state != *csrf.secret() {
println!("callback rejected: state {returned_state:?} does not match the one we sent");
continue;
}
match client
.exchange_code(AuthorizationCode::new(code))
.set_pkce_verifier(verifier)
.request_async(&http)
.await
{
Ok(t) => {
println!("token: type={:?} expires_in={:?} scopes={:?}", t.token_type(), t.expires_in(), t.scopes().map(|s| s.iter().map(|x| x.as_str()).collect::<Vec<_>>()));
println!("access={} refresh={}", t.access_token().secret(), t.refresh_token().unwrap().secret());
}
Err(e) => println!("exchange failed: {e}"),
}Two details in the types are worth noticing. access_token().secret() is the only way to read the token's text, and the token type itself prints as [redacted] under Debug, which is the same redaction pattern recommended for any secret: the leak has to be deliberate. And exchange_code returns a request builder, so the PKCE verifier is attached by a method call you can see in review, not by a hidden global.
The happy path, then the refresh
Run against the mock, the normal login prints the following. After the exchange, the program trades the refresh token for a new access token, the second thing a long-lived client does:
== happy path
authorize URL has: response_type, client_id, state, code_challenge, code_challenge_method, redirect_uri, scope
token: type=Bearer expires_in=Some(3600s) scopes=Some(["profile", "email"])
access=at-1 refresh=rt-1
refreshed: access=at-2 refresh=Some("rt-2")The first token expires in 3,600 seconds, so the client should refresh before then, or on the first 401. Notice that the refresh response carried a new refresh token, rt-2. Providers that rotate refresh tokens invalidate the old one when the new one is issued, so the client must store the replacement every time and handle two requests refreshing at once (serialise refreshes behind a lock). The crate returns the optional refresh token as an Option precisely because some providers omit it and mean "keep using the old one".
let r = client
.exchange_refresh_token(&RefreshToken::new("rt-1".into()))
.request_async(&http)
.await?;
println!("refreshed: access={} refresh={:?}", r.access_token().secret(), r.refresh_token().map(|x| x.secret().as_str()));Attack one: a forged callback
In the second scenario the program simulates an attacker who gets the victim's browser to load a callback URL with a state the victim never started. The returned state is replaced with attacker-chosen before the check:
== tampered state
authorize URL has: response_type, client_id, state, code_challenge, code_challenge_method, redirect_uri, scope
callback rejected: state "attacker-chosen" does not match the one we sentThe handler never contacts the token endpoint. This is the entire defence, and it is one comparison, which is why it is so often left out. Compare with a constant-time equality if you store the state in a place an attacker can probe, and fail closed: any missing or mismatched state ends the flow with an error page, not a retry.
Attack two: a stolen authorization code
The third scenario models an attacker who intercepted the code in the redirect, for example through a malicious app registered for the same custom URL scheme on a phone, or a proxy log. They try to redeem it with a verifier they guessed:
== stolen code, wrong verifier
authorize URL has: response_type, client_id, state, code_challenge, code_challenge_method, redirect_uri, scope
exchange failed: Server returned error response: invalid_grant: PKCE verification failedThe mock hashed the wrong verifier, compared it to the challenge it saw in step one, and refused. The error text comes straight from the provider's JSON body (error and error_description), which the crate formats for you; that is how you tell an expired code from a PKCE failure in a log. Without PKCE, the same stolen code would have been redeemed for a token. This is the concrete reason PKCE is recommended even for clients that have a secret: the secret proves who is redeeming, the verifier proves it is the same party that started the flow.
Attack three: replaying a code
Last, the legitimate code is redeemed once, successfully, and then presented again with a fresh, valid-looking verifier:
== code reuse
authorize URL has: response_type, client_id, state, code_challenge, code_challenge_method, redirect_uri, scope
token: type=Bearer expires_in=Some(3600s) scopes=Some(["profile", "email"])
access=at-1 refresh=rt-1
second exchange: Server returned error response: invalid_grant: authorization code already usedThe second call fails because codes are single-use. RFC 6749 goes further and says that on a replayed code the server should revoke the tokens already issued from it, since replay signals theft; my mock only rejects the second request and does not do that revocation, so test it against your actual provider rather than assuming it.
How the client proves who it is
PKCE shows that the party redeeming a code is the one that started the flow. A confidential client has a second job: telling the provider which application it is, using the secret. OAuth 2 allows two ways to send that secret to the token endpoint, and providers disagree about which they accept. The crate defaults to HTTP Basic and can be switched with set_auth_type. To see exactly what goes over the wire for each, I pointed the client at a throwaway listener that prints the request line and the interesting headers:
for (name, ty) in [("BasicAuth (the default)", AuthType::BasicAuth), ("RequestBody", AuthType::RequestBody)] {
let client = BasicClient::new(ClientId::new("demo-app".into()))
.set_client_secret(ClientSecret::new("demo-secret".into()))
.set_auth_uri(AuthUrl::new(format!("{base}/authorize")).unwrap())
.set_token_uri(TokenUrl::new(format!("{base}/token")).unwrap())
.set_auth_type(ty);
let t = client
.exchange_code(AuthorizationCode::new("c".into()))
.set_pkce_verifier(PkceCodeVerifier::new("v".into()))
.request_async(&http)
.await
.unwrap();
println!(" debug of token: {:?}", t.access_token());
}BasicAuth (the default)
POST /token HTTP/1.1
content-type: application/x-www-form-urlencoded
authorization: Basic ZGVtby1hcHA6ZGVtby1zZWNyZXQ=
grant_type=authorization_code&code=c&code_verifier=v
debug of token: AccessToken([redacted])
RequestBody
POST /token HTTP/1.1
content-type: application/x-www-form-urlencoded
grant_type=authorization_code&code=c&code_verifier=v&client_id=demo-app&client_secret=demo-secret
debug of token: AccessToken([redacted])With the default, the credentials ride in an Authorization: Basic header, and the base64 value decodes to demo-app:demo-secret. Base64 is an encoding and not encryption, which is the reason the token endpoint must be HTTPS in any real deployment. With RequestBody the secret is a form field in the POST body instead, and the header is absent. When a provider answers invalid_client to a request that looks right, this is the first setting to flip. Also notice what the last line of each block shows: the access token prints as AccessToken([redacted]). The crate's secret types override Debug, so a stray {:?} on a struct that holds a token does not leak it into a log. The text is available only through .secret(), a deliberate call that stands out in review.
A client with no secret
A command-line tool or a single-page app cannot hide a secret, because anyone can read the binary or the JavaScript. Such a client is a public client: leave out set_client_secret, and PKCE is then the only thing standing between a stolen code and a token. The typed builder supports this directly, and the exchange code is unchanged. That symmetry is the practical argument for writing the PKCE path first and treating the secret as an extra layer for server-side apps. If you do hold a secret, load it from the environment or a secret store at start-up, never from source control, and wrap it in a redacting type as shown for the crate's own tokens.
Testing a login without a real provider
The mock in this guide is worth copying in spirit, because OAuth bugs live in the cases a real provider will not produce on request. A provider will not hand you a forged state, a stolen code or a replayed one. A local stand-in, bound to port 0 so the operating system picks a free port and tests can run in parallel, can. Keep the mock to the rules that matter: record the challenge it saw, hash the verifier it is given, mark codes used, and answer in the provider's JSON error shape. Then write one test per attack and assert the exact error. The mock here is about sixty lines of hand-written HTTP; for a larger suite, a mocking crate such as wiremock removes the plumbing but not the need to decide what the fake provider enforces. Whatever you use, keep one end-to-end test against a real sandbox tenant in CI, because the mock only proves that the client agrees with your reading of the specification.
What a client has to get right outside the library
- Keep the state and verifier server-side, one use only. Tie them to the session that started the flow, expire them in minutes, and delete them on first use. A callback with no matching record is an error.
- Register exact redirect URIs. No wildcards, no open redirects on the same host. Use HTTPS for web clients;
http://localhostor a loopback address is the accepted exception for native tools. - Store tokens like passwords. Encrypt refresh tokens at rest, never log them, keep access tokens in memory where possible, and send them only in the
Authorizationheader, not in URLs. - Handle expiry and rotation. Refresh ahead of expiry, serialise refreshes, persist the new refresh token before using the new access token, and treat
invalid_granton refresh as "the user must sign in again". - Validate what you get. If you rely on an ID token for identity, you must verify its signature, issuer, audience and expiry; the
oauth2crate does not do this, and theopenidconnectcrate built on it does. - Ask for the least scope and show the user what you asked for.
Where this guide stops
- The provider was a mock. It implements the checks I wrote, in a few dozen lines of hand-rolled HTTP. Real providers differ: some require the client secret in the body, some in a Basic header, some reject scopes they do not know, and some return non-standard error shapes. Run your integration tests against a sandbox tenant before shipping.
- No browser was involved. The program followed the redirect by reading the
Locationheader. Cookies, consent screens, multi-factor prompts and the browser's own redirect-handling were not exercised. - Login is not the same as OAuth. OAuth 2 delegates access to an API. To identify a user, use OpenID Connect on top of it, which adds the ID token and the checks above.
- Server-to-server flows differ. A service with no user uses the client-credentials grant, which has no redirect, no state and no PKCE. The crate supports it, and this guide does not cover it.
- Device flow and other grants (for command-line tools without a browser) use a different sequence. The crate has the types for them; they are not shown here.
The measured outcomes fit in four lines: the normal login returned a bearer token valid for 3,600 seconds and refreshed to a rotated pair, a forged state stopped the flow before any network call, a stolen code failed with PKCE verification failed, and a replayed code failed with authorization code already used. Each of those is one decision in the client or the provider, and the library makes the right one the default.


