OAuth
OAuth is an authorization framework that allows third-party applications to access a user's data without sharing their credentials. It involves an authorization server and resource server, where users grant permission to apps to access their resources.
+---------+ +-----------------+ +--------------+
| User | | Authorization | | Resource |
| | | Server | | Server |
+----+----+ +--------+--------+ +------+-------+
| | |
| 1. Request Authorization | |
|--------------------------->| |
| | |
| 2. Redirect with Auth Code | |
|<---------------------------| |
| | |
| 3. Request Access Token | |
| with Auth Code | |
|--------------------------->| |
| | |
| 4. Return Access Token | |
|<---------------------------| |
| |
| 5. Access Resource using Access Token |
|-------------------------------------------------------->|
| |
| 6. Serve Resource |
|<--------------------------------------------------------|
| |
Implementing an OAuth Client
Let's take Github as an example. Go to Github and create an OAuth App.
You will need to fill in the The Authorization callback URL, which is a URL on your owner server.
When finished, you will get a client ID and a client secret.
The Authentication Process
-
Redirect user to Github's auth page at https://github.com/login/oauth/authorize?client_id={clientID} .
-
When succeed, Github will redirect to your application, with the auth code appended in the URL.
-
In your application where the callback URL points to, ask Github for access token using the auth code.
fetch("https://github.com/login/oauth/access_token", {
method: "POST",
headers: {
"content-type": "application/json",
accept: "application/json",
},
body: JSON.stringify({
client_id: clientID,
client_secret: clientSecret,
code: ctx.req.query('code'), // the auth code parsed from URL
})
})
-
Github issues the access token.
-
Ask Github for user info using access token.
fetch("https://api.github.com/user", {
headers: {
Accept: 'application/vnd.github+json',
Authorization: `Bearer ${access_token}`,
'User-Agent': '<your app>',
'X-GitHub-Api-Version': '2022-11-28',
}
})
- Github returns user info.