GitHub OAuth2.0 middleware for the TezX web framework. Securely authenticate users via GitHub, and define custom sign-in, session, and token handling logic.
Go to: https://github.com/settings/developers
- Click "New OAuth App"
- Name:
My GitHub Login App
- Homepage URL:
http://localhost:3000
- Authorization callback URL:
http://localhost:3000/auth/github/callback
- Save and copy
Client ID
andClient Secret
npm install @tezx/github-oauth2
import { TezX } from 'tezx';
import {
GitHubOauthClient,
getGithubOAuthURL,
verifyGithubToken
} from '@tezx/github-oauth2';
const app = new TezX({
debugMode: true
});
// Initialize OAuth client
const client = GitHubOauthClient({
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
redirectUri: 'http://localhost:3000'
});
// Step 1: Redirect user to GitHub login
app.get('github', getGithubOAuthURL({
authClient: client,
}), (ctx) => {
return ctx.redirect(ctx.state.get('github_oauth_url'));
});
// Step 2: Verify GitHub token and handle user session
app.get('/', verifyGithubToken({
authClient: client,
Callbacks: (ctx) => {
return {
session: async (session, user) => {
console.log('Session:', session);
console.log('User:', user);
return session;
}
};
}
}), async (ctx) => {
return ctx.json({ success: true });
});
Creates an OAuth client instance.
Name | Type | Description |
---|---|---|
clientId | string | GitHub OAuth App client ID |
clientSecret | string | GitHub OAuth App client secret |
redirectUri | string | URI GitHub should redirect to |
Generates the GitHub OAuth URL and stores it in ctx.state.get('github_oauth_url')
.
Name | Type | Description |
---|---|---|
authClient | GitHubOauthClient | The OAuth client instance |
scopes | string[] | (Optional) OAuth scopes (default: ['read:user', 'user:email'] ) |
state | string | (Optional) CSRF protection state value |
allowSignup | boolean | (Optional) Allow GitHub signups (default: true) |
Middleware to validate the token returned from GitHub and handle user info.
Name | Type | Description |
---|---|---|
authClient | GitHubOauthClient | The initialized OAuth client |
Callbacks | (ctx) => CallbacksReturn |
Optional lifecycle methods |
Method | Description |
---|---|
signIn(user) |
Called after user is authenticated. Return true to allow login. |
jwt(token, user?) |
Customize JWT token if applicable. |
session(session, user) |
Customize the session object before sending to client. |
Always validate the state
returned from GitHub against a CSRF token stored on your server before accepting the response.