如何基于TMDB API实现用户认证及Auth Token获取流程
Hey there! I’ve worked with TMDB’s authentication flow before, so let me walk you through exactly how to implement this step by step—perfect for your Android app use case.
First, let’s break down TMDB’s core auth flow to make sure we’re on the same page:
- Request a request token using your API key.
- Send the user to TMDB’s official login/authorization page (via browser) with this token.
- After the user logs in/approves your app, TMDB marks the request token as valid.
- Exchange the approved request token for a session ID (this is the "auth token" you’ll use for user-specific API calls).
Now let’s dive into the code implementation:
Step 1: Fetch a Request Token
First, call TMDB’s authentication/token/new endpoint to get a temporary request token. Here’s a quick example using OkHttp:
val client = OkHttpClient() val request = Request.Builder() .url("https://api.themoviedb.org/3/authentication/token/new?api_key=YOUR_API_KEY") .get() .build() client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { // Handle network errors here } override fun onResponse(call: Call, response: Response) { val responseJson = response.body?.string() ?: return // Parse the JSON to extract the request_token (and note its expiration time) // Sample response: {"success":true,"expires_at":"2024-05-20T14:30:00Z","request_token":"abc123xyz"} val requestToken = // extract from parsed JSON // Store this token temporarily (e.g., SharedPreferences) } })
Step 2: Launch TMDB’s Login Page in a Browser
Once you have the request token, create an intent to open the browser with TMDB’s authorization URL. You’ll need to register a redirect URI in your TMDB account settings (under "API" > "Redirect URLs")—use a custom scheme like yourapp://tmdb-auth-callback so your app can catch the user’s return.
val requestToken = // retrieve from SharedPreferences val authUrl = "https://www.themoviedb.org/authenticate/$requestToken?redirect_to=yourapp://tmdb-auth-callback" val intent = Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)) startActivity(intent)
Step 3: Handle the Redirect Back to Your App
Set up a deep link handler to catch the redirect when the user finishes logging in:
- Add an intent filter to your
AndroidManifest.xmlfor your custom scheme:
<activity android:name=".AuthCallbackActivity"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="yourapp" android:host="tmdb-auth-callback" /> </intent-filter> </activity>
- In
AuthCallbackActivity, verify the authorization status and grab the approved request token:
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) intent.data?.let { uri -> val requestToken = uri.getQueryParameter("request_token") val isApproved = uri.getQueryParameter("approved") == "true" if (isApproved && requestToken != null) { // Proceed to exchange the token for a session ID exchangeTokenForSession(requestToken) } else { // User canceled or authorization failed—handle this case } } finish() // Close this helper activity immediately }
Step 4: Exchange Request Token for a Session ID
Now that the request token is approved, call the authentication/session/new endpoint to get a permanent (well, long-lived) session ID—this is the token you’ll use for authenticated API calls:
fun exchangeTokenForSession(requestToken: String) { val client = OkHttpClient() val formBody = FormBody.Builder() .add("request_token", requestToken) .build() val request = Request.Builder() .url("https://api.themoviedb.org/3/authentication/session/new?api_key=YOUR_API_KEY") .post(formBody) .build() client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { // Handle errors } override fun onResponse(call: Call, response: Response) { val responseJson = response.body?.string() ?: return // Parse JSON to extract the session_id // Sample response: {"success":true,"session_id":"def456uvw"} val sessionId = // extract from parsed JSON // Store this session ID securely (use EncryptedSharedPreferences for best practice) // Now you can use this session ID in calls like marking movies as favorite or accessing user watchlists } }) }
Quick Key Notes:
- Security: Never hardcode your API key in the app—use build config variables or secure storage. Always encrypt the session ID to protect user data.
- Expiration: Request tokens expire after 60 minutes, so add logic to check the expiration time and request a new token if needed.
- OAuth2 Alternative: If you want a longer-lived access token (for things like offline access), TMDB has an OAuth2 flow that uses authorization codes. Let me know if you want details on that!
内容的提问来源于stack exchange,提问作者Taylor

