Skip to content

feat: Add OAuth 2.0 support with PKCE flow - #6940

Open
Kota-Jagadeesh wants to merge 32 commits into
commons-app:mainfrom
Kota-Jagadeesh:feat/OAuth
Open

Kota-Jagadeesh wants to merge 32 commits into
commons-app:mainfrom
Kota-Jagadeesh:feat/OAuth

Conversation

@Kota-Jagadeesh

Copy link
Copy Markdown
Collaborator

Description (required)

Fixes #6885

  • implemented OAuth 2.0 authorization code grant flow with PKCE to enable thesecure web-based login via chrome custom tabs.
  • configured the custom scheme deep-linking (fr.free.nrw.commons://oauth-callback) in AndroidManifest.xml to intercept post-auth redirects.
  • and addedthe token exchange (/w/rest.php/oauth2/access_token) and profile fetching (/w/rest.php/oauth2/resource/profile) in LoginInterface, securely persisting access_token and refresh_token in SessionManager via Android the accountmanager.
  • updated the NetworkingModule to automatically attach Authorization: Bearer <access_token> headers to the outgoing API requests.
  • also added a "Login with OAuth" option to activity_login.xml

Tests performed (required)

Tested ProdDebug on Redmi Note 13 PRO with API level 36. Verified web authentication flow, deep-link callback execution, token persistence, and successful account contributions fetching.

Screenshots (for UI changes only)

Screenrecorder-2026-08-09-21-31-53-10.mp4
image

@RitikaPahwa4444

Copy link
Copy Markdown
Collaborator

I'm getting this error page on this branch:

screen-20260810-020943.mp4

@Kota-Jagadeesh

Kota-Jagadeesh commented Aug 10, 2026 •

Copy link
Copy Markdown
Collaborator Author

ahh, @RitikaPahwa4444 that is expected. as the OAuth 2.0 consumer keys aren't committed here(git) , build.gradle.kts falls back to empty strings if they aren't present in local.properties

@Kota-Jagadeesh

Copy link
Copy Markdown
Collaborator Author

I'm getting this error page on this branch:

I'll mail you and @nicolas-raoul my developer client keys in some time, so you can use them in local.properties and test the auth flow directly

@chrisdebian chrisdebian left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for building this out — the PKCE implementation itself is correct: SecureRandom with 32 bytes for the verifier, SHA-256 + base64url for the challenge, S256 as the method, all matching RFC 7636. Found three real issues around it though, all in how the tokens it protects get handled afterward.

1. Shipping a client_secret alongside PKCE defeats the reason to use PKCE at all. grantOAuthToken() sends client_secret = BuildConfig.OAUTH_CLIENT_SECRET, compiled in from local.properties. PKCE exists specifically so a public client — anything that can't keep a secret, which by definition includes a distributed Android APK — doesn't need one (RFC 8252, "OAuth 2.0 for Native Apps," is explicit that native apps must be treated as public clients and must not use client secrets). Whatever value ends up in OAUTH_CLIENT_SECRET is trivially recoverable from any built APK via jadx/dex2jar, so it provides no actual protection — it's PKCE doing the real work here regardless of whether the secret is present. Suggest dropping client_secret entirely and registering the app's OAuth consumer as a public client, matching what PKCE is for.

2. refresh_token is stored more weakly than access_token, and more weakly than this codebase's own existing convention. SessionManager.updateOAuthAccount() puts the access token in accountManager.setAuthToken() (the auth-token slot, correctly access-controlled) but the refresh token in accountManager.setUserData() — the general-purpose metadata bag, not designed for secrets. The refresh token is the longer-lived, more valuable of the two credentials (usable to mint fresh access tokens until revoked), so if anything it deserves more protection, not less. Worth noting the existing password-based login path already treats its one secret correctly, via accountManager.setPassword()/getPassword() — the strongest single-value slot AccountManager offers. The new OAuth path doesn't extend that same care to the refresh token.

3. The bearer token gets attached to every outgoing request on the shared OkHttpClient, not just requests to the host that issued it. The new interceptor in NetworkingModule.provideOkHttpClient() adds Authorization: Bearer <accessToken> unconditionally, with no check on chain.request().url.host. That OkHttpClient singleton is the same instance wired into provideOkHttpJsonApiClient() a few lines below, which serves tools_forge (Toolforge), WIKIDATA_SPARQL_QUERY_URL, and BuildConfig.WIKIMEDIA_CAMPAIGNS_URL — three genuinely different hosts, none of which are the OAuth resource server. As written, a logged-in user's access token would be sent as a header to all of them. Suggest scoping the interceptor to the specific host(s) the token is actually valid for before this merges.

Smaller note, not blocking: the authorization request in startOAuthLogin() has no state parameter. PKCE already covers the main authorization-code-injection threat this would traditionally guard against, so it's a defence-in-depth gap rather than an open hole, but worth adding for completeness per the usual OAuth 2.0 guidance (RFC 6749 §10.12).

Happy to go into more detail on any of these.

@Kota-Jagadeesh

Copy link
Copy Markdown
Collaborator Author

@nicolas-raoul @RitikaPahwa4444 Any good news on OAuth? Do we have plans to implement this for next release?

@RitikaPahwa4444

Copy link
Copy Markdown
Collaborator

Yes, login needs to be fixed on priority: #6906. I couldn't get a chance to test it again but I'll try again over this weekend.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Credential exposure, incomplete API authentication, and OAuth lifecycle and recovery defects block safe use.

Review effort: Balanced
Findings: 3 High severity · 6 Medium severity

Open (9)
What changed in this PR

Adds browser-based OAuth 2.0 login with PKCE alongside the existing Commons login flow, addressing #6885.

Changes:

  • Adds OAuth login controls, browser authorization, and callback handling.
  • Introduces token exchange, profile fetching, and account token storage.
  • Adds bearer-token attachment and OAuth build configuration.
File Description
app/​src/​main/​res/​values/​strings.xml Adds OAuth login label.
app/​src/​main/​res/​layout/​activity_login.xml Adds OAuth login button.
app/​src/​main/​java/​fr/​free/​nrw/​commons/​di/​NetworkingModule.kt Adds bearer-token interceptor.
app/​src/​main/​java/​fr/​free/​nrw/​commons/​auth/​SessionManager.kt Stores OAuth account credentials.
app/​src/​main/​java/​fr/​free/​nrw/​commons/​auth/​LoginActivity.kt Implements browser authorization and callbacks.
app/​src/​main/​java/​fr/​free/​nrw/​commons/​auth/​login/​OAuthTokenResponse.kt Models token responses.
app/​src/​main/​java/​fr/​free/​nrw/​commons/​auth/​login/​OAuthProfileResponse.kt Models profile responses.
app/​src/​main/​java/​fr/​free/​nrw/​commons/​auth/​login/​LoginInterface.kt Defines OAuth endpoints.
app/​src/​main/​java/​fr/​free/​nrw/​commons/​auth/​login/​LoginClient.kt Adds token exchange and profile requests.
app/​src/​main/​AndroidManifest.xml Registers OAuth callback deep link.
app/​build.gradle.kts Loads OAuth client configuration.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread app/build.gradle.kts Resolved
@Kota-Jagadeesh

Copy link
Copy Markdown
Collaborator Author

with the issue #6906 being ressolved, i will look into the copilot review comments and get the possible fix for the relavant ones

@Kota-Jagadeesh

Copy link
Copy Markdown
Collaborator Author

I've fixed the important issues and am now waiting for the client key to be approved by the steward. Once it's approved, I'll test the changes and push them

@Kota-Jagadeesh

Copy link
Copy Markdown
Collaborator Author

Tested the flow and everything works fine :) Willl update the PR shortly

@nicolas-raoul

Copy link
Copy Markdown
Member

Would you mind checking the "Android CI / Run tests and generate APK" failures? Thanks!

@nicolas-raoul

Copy link
Copy Markdown
Member

Specifically:

app/src/main/java/fr/free/nrw/commons/auth/LoginActivity.kt:150:17: The function handleOAuthCallback appears to be too complex based on Cyclomatic Complexity (complexity: 16). Defined complexity threshold for methods is set to '15' [CyclomaticComplexMethod]
app/src/main/java/fr/free/nrw/commons/auth/SessionManager.kt:21:7: Class 'SessionManager' with '11' functions detected. Defined threshold inside classes is set to '11' [TooManyFunctions]
app/src/main/java/fr/free/nrw/commons/OkHttpConnectionFactory.kt:76:13: This condition is too complex (4). Defined complexity threshold for conditions is set to '4' [ComplexCondition]
app/src/main/java/fr/free/nrw/commons/di/NetworkingModule.kt:78:17: This condition is too complex (4). Defined complexity threshold for conditions is set to '4' [ComplexCondition]
app/src/main/java/fr/free/nrw/commons/auth/login/OAuthTokenResponse.kt:12:2: The file app/src/main/java/fr/free/nrw/commons/auth/login/OAuthTokenResponse.kt is not ending with a new line. [NewLineAtEndOfFile]
app/src/main/java/fr/free/nrw/commons/auth/login/OAuthProfileResponse.kt:9:2: The file app/src/main/java/fr/free/nrw/commons/auth/login/OAuthProfileResponse.kt is not ending with a new line. [NewLineAtEndOfFile]
app/src/main/java/fr/free/nrw/commons/auth/LoginActivity.kt:599:1: Line detected, which is longer than the defined maximum line length in the code style. [MaxLineLength]
app/src/main/java/fr/free/nrw/commons/auth/LoginActivity.kt:215:30: This expression contains a magic number. Consider defining it to a well named constant. [MagicNumber]

app/src/main/java/fr/free/nrw/commons/auth/login/LoginInterface.kt:52:53 Missing trailing comma before ")"
app/src/main/java/fr/free/nrw/commons/auth/login/LoginInterface.kt:62:51 Missing trailing comma before ")"
app/src/main/java/fr/free/nrw/commons/auth/login/OAuthProfileResponse.kt:8:48 Missing trailing comma before ")"
app/src/main/java/fr/free/nrw/commons/auth/login/OAuthProfileResponse.kt:9:1 File must end with a newline (\n)
app/src/main/java/fr/free/nrw/commons/auth/login/OAuthTokenResponse.kt:11:52 Missing trailing comma before ")"
app/src/main/java/fr/free/nrw/commons/auth/login/OAuthTokenResponse.kt:12:1 File must end with a newline (\n)

@Kota-Jagadeesh

Copy link
Copy Markdown
Collaborator Author

UploadActivityUnitTests > needsMediaLocationPermissionIsFalseWithThePermission FAILED
java.lang.AssertionError at MavenArtifactFetcher.java:129
Caused by: java.util.concurrent.ExecutionException at AbstractFuture.java:596
Caused by: java.io.IOException at HttpURLConnection.java:2059

UploadActivityUnitTests > needsMediaLocationPermissionIsTrueWithoutThePermission FAILED
java.lang.AssertionError at MavenArtifactFetcher.java:129
Caused by: java.util.concurrent.ExecutionException at AbstractFuture.java:596
Caused by: java.io.IOException at HttpURLConnection.java:2059

UploadActivityUnitTests > sharedItemsAreReceivedRightAwayWhenMediaLocationIsGranted FAILED
java.lang.AssertionError at MavenArtifactFetcher.java:129
Caused by: java.util.concurrent.ExecutionException at AbstractFuture.java:596
Caused by: java.io.IOException at HttpURLConnection.java:2059
OpenJDK 64-Bit Server VM warning: Sharing is only supported for boot loader classes because bootstrap classpath has been appended

@nicolas-raoul i ran the unit tests locally and they pass in my machinee, looking at the above stack trace ig roboelectric hit a transient network hiccup while fetching the sdk jar from maveen. could you re run the failed ci job?

@Kota-Jagadeesh

Copy link
Copy Markdown
Collaborator Author

@nicolas-raoul This is ready to test :)

@nicolas-raoul

Copy link
Copy Markdown
Member

Thanks @Kota-Jagadeesh, CI is green now! client_secret is gone and the bearer token is only sent to the allowed hosts, good. A few things I noticed in the diff before testing:

  1. Landscape loses the password login button. In layout-land/activity_login.xml the login_button is replaced by oauth_login_button instead of being kept next to it, so in landscape there is no "Log in" button anymore (and loginButton became nullable in LoginActivity). Could you keep login_button there and add the OAuth button below buttonFrame, like in the portrait layout?
  2. Refresh token: it is still stored with accountManager.setUserData() (second point of the review above) and nothing reads it yet. What happens when the access token expires? If refreshing is for a later PR, it may be simpler to not store the refresh token for now.
  3. Hard-coded English messages in LoginActivity ("OAuth login failed", "OAuth verification session expired. Please try logging in again.", "OAuth Token Exchange Failed"): please move them to strings.xml (with values-qq entries).
  4. Minor: the allowed-hosts check is duplicated in OkHttpConnectionFactory and NetworkingModule; one shared interceptor with a unit test would be nice.

Thanks!

@Kota-Jagadeesh

Copy link
Copy Markdown
Collaborator Author

@nicolas-raoul thanks for the feedback! all four issues are addressed, landscape layout now keeps login_button alongside oauth_login_button below buttonFrame, unused refresh token storage is removed, OAuth error strings are moved to strings.xml + values-qq, and OAuthTokenInterceptor is deduplicated with unit tests added :)

@nicolas-raoul nicolas-raoul left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the quick update @Kota-Jagadeesh! Three points from reading the updated diff:

  1. Duplicate OAuthTokenInterceptor still present in OkHttpConnectionFactory.kt:
    app/src/main/java/fr/free/nrw/commons/auth/OAuthTokenInterceptor.kt was added, but a second class OAuthTokenInterceptor : Interceptor was also left inside OkHttpConnectionFactory.kt (package fr.free.nrw.commons, lines 69–136), and OkHttpConnectionFactory instantiates that local copy instead of fr.free.nrw.commons.auth.OAuthTokenInterceptor. Please delete the duplicate class in OkHttpConnectionFactory.kt and import fr.free.nrw.commons.auth.OAuthTokenInterceptor.

  2. oauth_login_button is visible even when OAUTH_CLIENT_ID is not configured:
    getOAuthClientId() defaults to "YOUR_OAUTH_CLIENT_ID" when local.properties has no OAUTH_CLIENT_ID (for example in local contributor builds, CI APKs, or F-Droid builds). Tapping Log in with OAuth in that state opens Meta-Wiki with client_id=YOUR_OAUTH_CLIENT_ID, which fails immediately. Could LoginActivity hide oauthLoginButton whenever BuildConfig.OAUTH_CLIENT_ID.isBlank() || BuildConfig.OAUTH_CLIENT_ID == "YOUR_OAUTH_CLIENT_ID"?

  3. Access token expiry (4 hours on Wikimedia OAuth 2.0):
    Unless an OAuth 2.0 client is owner-only, Wikimedia OAuth 2.0 access tokens issued via the authorization-code/PKCE flow expire after 4 hours. Without refreshing via refresh_token, won't uploads and edits start failing with HTTP 401 four hours after logging in? How did this behave in your testing?

@Kota-Jagadeesh

Kota-Jagadeesh commented Nov 29, 2026 •

Copy link
Copy Markdown
Collaborator Author

Access token expiry (4 hours on Wikimedia OAuth 2.0):
Unless an OAuth 2.0 client is owner-only, Wikimedia OAuth 2.0 access tokens issued via the authorization-code/PKCE flow expire after 4 hours. Without refreshing via refresh_token, won't uploads and edits start failing with HTTP 401 four hours after logging in? How did this behave in your testing?

in my testing, login and upload, edit worked fine within the 4 hour window, so i hadn't hit the 401 yet. and without refresh_token handling, requests will indeed fail with http 401 once the token expires.

so, would you prefer that i add the refresh_token renewal flow in this pr, or keep this pr focused on the initial oauth login and handle refresh in a follow up pr?

@github-actions

Copy link
Copy Markdown

✅ Generated APK variants!

@nicolas-raoul

Copy link
Copy Markdown
Member

same pr is best, thanks! :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add OAuth Support

5 participants