OAuth2无OIDC时的用户身份识别及API工作原理问询
Great question! Let's break this down clearly, since OAuth2 and OIDC serve different core purposes, and it's super common to encounter OAuth2-only APIs.
First, a key clarification: OAuth2 was never designed for user authentication—its sole job is to handle authorization: granting third-party apps (like your mobile app) permission to access specific resources on behalf of a user. It has no built-in way to identify "who the user is" out of the box. That's exactly why OIDC was created later: to bolt user authentication onto OAuth2 via the id_token.
So when dealing with an OAuth2-only API, here's how you typically handle user identification:
1. The Go-To: User Info Endpoints (Like /me)
This is the most standard approach. After your mobile app obtains an access_token via an OAuth2 flow (always use PKCE for mobile apps, by the way), you'll call a dedicated user information endpoint provided by the OAuth2 server. Common endpoint names include /me, /userinfo, or /api/v1/user.
To make this call:
- Include the
access_tokenin the request header (usually using theAuthorization: Bearer <your-access-token>format). - The OAuth2 server will validate the token (check if it's valid, unexpired, and has the right scopes) and return user-specific data, which almost always includes a unique user identifier (like
user_id,sub, or a platform-specific ID).
For example:
GET /userinfo HTTP/1.1 Host: oauth.example.com Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
The response might look like:
{ "user_id": "123456", "username": "dannyboy", "email": "danny@example.com" }
You'll store that user_id locally in your mobile app to identify the authenticated user going forward.
2. Other Non-Standard Approaches
Some OAuth2 providers might offer alternative ways to get user info, though these aren't part of the OAuth2 spec:
- Included user ID in token response: A few providers add a
user_idfield directly in the initial token response (alongsideaccess_tokenandrefresh_token). This is convenient but not universal. - JWT-formatted access tokens: If the
access_tokenis a JWT (JSON Web Token), you can decode it client-side to extract user claims likesub(subject, the user's unique ID). But be cautious: you should always verify the JWT's signature to prevent tampering, and not all OAuth2 access tokens are JWTs (many are opaque strings that can't be decoded client-side).
3. How the Resource Server Handles It
Behind the scenes, the OAuth2 resource server (the API you're calling) maintains a mapping between access_tokens and the users they belong to. When you send an access_token with an API request, the resource server checks its validity and looks up the associated user to enforce permissions or return user-specific data.
In short: Without OIDC, you rely on additional API calls (like /me) to get the user's identity after obtaining an access_token—this fills the gap that OIDC's id_token solves natively.
内容的提问来源于stack exchange,提问作者Dannyboy

