Bitbucket OAuth2
Authorization Code Exchange for web and mobile — Bitbucket OAuth consumer setup, API reference, and frontend examples.
Overview
Bitbucket login is optional and controlled by BITBUCKET_AUTH_ENABLED. When disabled, Bitbucket endpoints return 503 Service Unavailable. JWTs are never placed in the redirect URL; the API issues a one-time exchangeCode (Redis, 60 seconds). The same POST /auth/exchange endpoint is shared with other social providers.
- • Feature-flagged via environment
- • Custom passport-oauth2 strategy + BitbucketAuthGuard
- • Profile fetched via GET https://api.bitbucket.org/2.0/user and GET https://api.bitbucket.org/2.0/user/emails after token exchange
- • Scopes account and email for profile and primary email
- • Redirect allowlist prevents open redirects
- • Same token response shape as POST /auth/login
Bitbucket OAuth consumers
Create an OAuth consumer under Bitbucket → Workspace settings → OAuth consumers (or Personal settings → OAuth consumers, also listed as Settings → OAuth consumers / Apps and features). Set the Callback URL to match BITBUCKET_CALLBACK_URL. Enable the account and email scopes.
- Open Bitbucket → Workspace settings → OAuth consumers (or Personal settings → OAuth consumers / Apps and features)
- Click Add consumer
- Set the Callback URL (e.g. http://localhost:3000/api/v1/auth/bitbucket/callback)
- Enable the account and email scopes
- Copy Key and Secret into your .env
- Ensure BITBUCKET_CALLBACK_URL matches the Callback URL registered in Bitbucket
Environment variables
Loaded from .env via src/config/bitbucket-oauth.config.ts (namespace bitbucketOAuth on ConfigService). See .env.example.
BITBUCKET_AUTH_ENABLED=true BITBUCKET_CLIENT_ID=your-bitbucket-consumer-key BITBUCKET_CLIENT_SECRET=your-bitbucket-consumer-secret BITBUCKET_CALLBACK_URL=http://localhost:3000/api/v1/auth/bitbucket/callback BITBUCKET_REDIRECT_ALLOWLIST=myapp://success,http://localhost:5173/auth/callback BITBUCKET_OAUTH_DEFAULT_ROLES=
Default roles for new Bitbucket users
New Bitbucket users receive roles: [] by default (same as password register). Set BITBUCKET_OAUTH_DEFAULT_ROLES in .env to a comma-separated list of Role values (e.g. user or user,manager). Existing users linked by email keep their current roles.
Sequence
- Client opens GET /api/v1/auth/bitbucket?redirect=<allowlisted URL>
- User consents on Bitbucket; browser hits GET /api/v1/auth/bitbucket/callback
- API calls GET https://api.bitbucket.org/2.0/user and /user/emails, upserts user, stores exchangeCode in Redis, redirects to redirect?code=...
- Client POSTs { code } to /api/v1/auth/exchange and receives JWTs
API reference
1. Start OAuth
Opens Bitbucket consent at https://bitbucket.org/site/oauth2/authorize. Query redirect must match a prefix in BITBUCKET_REDIRECT_ALLOWLIST (or omit to use the first allowlist entry). Scopes: account email.
GET /api/v1/auth/bitbucket?redirect=http%3A%2F%2Flocalhost%3A5173%2Fauth%2Fcallback
400 invalid redirect · 503 feature disabled
2. Callback
Handled by the API. Token exchange uses https://bitbucket.org/site/oauth2/access_token. Redirects to your app with ?code= (or &code= if the URL already has a query).
GET /api/v1/auth/bitbucket/callback?code=BITBUCKET_AUTH_CODE&state=... → 302 Location: http://localhost:5173/auth/callback?code=EXCHANGE_CODE
3. Exchange code
Public endpoint shared with other social providers. Consumes the code (single use) and returns the same shape as login.
POST /api/v1/auth/exchange
Content-Type: application/json
{
"code": "EXCHANGE_CODE"
}{
"user": {
"id": "...",
"email": "[email protected]",
"firstName": "Jane",
"lastName": "Doe",
"roles": [],
"bitbucketId": "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}",
"isActive": true
},
"accessToken": "eyJhbGciOiJIUzI1NiIs...",
"refreshToken": "eyJhbGciOiJIUzI1NiIs..."
}401 invalid/expired/used code · 503 social auth disabled
Frontend — Web (SPA)
Typical flow: button starts OAuth in the same window (or popup); a callback route on your frontend origin reads code from the query string and calls exchange.
const API = 'http://localhost:3000/api/v1';
const redirect = encodeURIComponent(
'http://localhost:5173/auth/callback'
);
// Full-page redirect to Nest → Bitbucket → back to SPA
window.location.href = `${API}/auth/bitbucket?redirect=${redirect}`;// /auth/callback on the SPA
const params = new URLSearchParams(window.location.search);
const code = params.get('code');
if (!code) throw new Error('Missing exchange code');
const res = await fetch('http://localhost:3000/api/v1/auth/exchange', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code }),
});
if (!res.ok) throw new Error(await res.text());
const { user, accessToken, refreshToken } = await res.json();
// persist tokens as your app requires
sessionStorage.setItem('accessToken', accessToken);
console.log('signed in', user.email);- • Add your frontend callback URL to BITBUCKET_REDIRECT_ALLOWLIST (e.g. http://localhost:5173/auth/callback)
- • BITBUCKET_CALLBACK_URL must point at the Nest API, not the SPA
- • Store accessToken / refreshToken securely (memory + httpOnly cookie patterns as you prefer)
Frontend — Mobile (deep link)
Use a custom scheme (or universal link) in the allowlist. After Bitbucket, the API redirects to myapp://success?code=.... The app opens, parses the code, and calls exchange.
import * as Linking from 'expo-linking';
import * as WebBrowser from 'expo-web-browser';
const API = 'https://api.example.com/api/v1';
const redirect = encodeURIComponent('myapp://success');
async function signInWithBitbucket() {
const url = `${API}/auth/bitbucket?redirect=${redirect}`;
await WebBrowser.openAuthSessionAsync(url, 'myapp://success');
}import * as Linking from 'expo-linking';
async function exchangeFromUrl(url) {
const { queryParams } = Linking.parse(url);
const code = queryParams?.code;
if (!code) return;
const res = await fetch(`${API}/auth/exchange`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code }),
});
const data = await res.json();
// data.accessToken, data.refreshToken, data.user
return data;
}
Linking.addEventListener('url', ({ url }) => {
exchangeFromUrl(url);
});- • Register the scheme in the OS / Expo app.json
- • Prefer Linking.addEventListener('url', ...) and getInitialURL()
- • Exchange over HTTPS against your API base URL
Security notes
- • Redirect URLs must match BITBUCKET_REDIRECT_ALLOWLIST prefixes
- • Exchange codes are single-use and expire in 60 seconds (Redis)
- • Existing local users are linked by verified Bitbucket email (bitbucketId set; roles unchanged)
- • Bitbucket-only users have password null — password login / change-password will fail until a password is set
- • Email is required from api.bitbucket.org/2.0/user/emails; login fails if Bitbucket does not return a primary or confirmed email (scopes account and email)
User model
Postgres entity / interface fields used by Bitbucket login:
- • bitbucketId — unique nullable Bitbucket user UUID (uuid from /2.0/user)
- • password — nullable for OAuth-only accounts
- • isActive — set true for new Bitbucket users
- • roles — from BITBUCKET_OAUTH_DEFAULT_ROLES env (default [])
Related
- Social Authentication hub
- Google OAuth2 guide
- Facebook OAuth2 guide
- X / Twitter OAuth2 guide
- GitHub OAuth2 guide
- Figma OAuth2 guide
- LinkedIn OpenID Connect guide
- Slack OpenID Connect guide
- Atlassian OAuth 2.0 (3LO) guide
- GitLab OAuth2 guide
- Discord OAuth2 guide
- Twitch OAuth2 guide
- Steam OpenID 2.0 guide
- Reddit OAuth2 guide
- Auth & JWT