GitHub OAuth Authentication Implementation for Websites
GitHub OAuth is used on developer platforms, DevTools services, and SaaS products with technical audiences. One of the cleanest OAuth2 flows—no surprises with email or names.
Registering OAuth App
- github.com → Settings → Developer settings → OAuth Apps → New OAuth App
- Fill: Application name, Homepage URL, Authorization callback URL
- Save Client ID and generate Client Secret
GitHub App (not OAuth App) is for repository and organization access—OAuth App is sufficient for user authorization.
Laravel Socialite
// config/services.php
'github' => [
'client_id' => env('GITHUB_CLIENT_ID'),
'client_secret' => env('GITHUB_CLIENT_SECRET'),
'redirect' => env('GITHUB_REDIRECT_URI'),
],
class GitHubAuthController extends Controller
{
public function redirect(): RedirectResponse
{
return Socialite::driver('github')
->scopes(['user:email'])
->redirect();
}
public function callback(): RedirectResponse
{
try {
$githubUser = Socialite::driver('github')->user();
} catch (\Exception $e) {
return redirect('/login')->withErrors(['github' => 'GitHub authorization error']);
}
$user = User::updateOrCreate(
['github_id' => $githubUser->getId()],
[
'name' => $githubUser->getName() ?? $githubUser->getNickname(),
'email' => $githubUser->getEmail(),
'email_verified_at' => now(),
'avatar' => $githubUser->getAvatar(),
'github_username' => $githubUser->getNickname(),
]
);
Auth::login($user, remember: true);
return redirect()->intended('/dashboard');
}
}
GitHub OAuth Features
Email may be private. If user hid email in GitHub settings, getEmail() returns null. Request with user:email scope allows fetching email via additional API request:
// Explicit request for emails via API
$emails = Http::withToken($githubUser->token)
->get('https://api.github.com/user/emails')
->json();
// Find primary confirmed email
$primaryEmail = collect($emails)
->firstWhere(fn($e) => $e['primary'] && $e['verified']);
Avatar: URL like https://avatars.githubusercontent.com/u/{id}?v=4—stable, doesn't expire.
GitHub username: Useful for profile display or creating link to user's GitHub profile.
Organization Restriction
To allow login only for members of specific GitHub organization:
$membership = Http::withToken($githubUser->token)
->get("https://api.github.com/orgs/{$orgName}/members/{$githubUser->getNickname()}");
if ($membership->status() !== 204) {
Auth::logout();
return redirect('/login')->withErrors(['github' => 'Access restricted to organization members']);
}
Timeline
1–2 days.







