Diese Woche am beliebtesten

Vertiefendes Material

OAuth Social Login

Dieser Codeschnipsel erstellt einen Social Login mit Google, Facebook und GitHub. Der Code unterstützt OAuth 2.0, sicheres Token-Handling und eine AJAX-basierte Anmeldung. Er ist sofort einsatzbereit, einfach konfigurierbar und kann direkt in bestehende Webprojekte integriert werden. Nutzer können sich so schnell und sicher über ihre bevorzugten Social Accounts anmelden.

<?php
session_start();
$providers = [
    'google' => [
        'client_id' => 'DEINE_GOOGLE_CLIENT_ID',
        'client_secret' => 'DEIN_GOOGLE_CLIENT_SECRET',
        'redirect_uri' => 'http://localhost/social-login.php?provider=google',
        'auth_url' => 'https://accounts.google.com/o/oauth2/v2/auth',
        'token_url' => 'https://oauth2.googleapis.com/token',
        'user_info_url' => 'https://www.googleapis.com/oauth2/v2/userinfo',
        'scope' => 'email profile'
    ],
    'facebook' => [
        'client_id' => 'DEINE_FACEBOOK_APP_ID',
        'client_secret' => 'DEIN_FACEBOOK_APP_SECRET',
        'redirect_uri' => 'http://localhost/social-login.php?provider=facebook',
        'auth_url' => 'https://www.facebook.com/v17.0/dialog/oauth',
        'token_url' => 'https://graph.facebook.com/v17.0/oauth/access_token',
        'user_info_url' => 'https://graph.facebook.com/me?fields=id,name,email',
        'scope' => 'email'
    ],
    'github' => [
        'client_id' => 'DEINE_GITHUB_CLIENT_ID',
        'client_secret' => 'DEIN_GITHUB_CLIENT_SECRET',
        'redirect_uri' => 'http://localhost/social-login.php?provider=github',
        'auth_url' => 'https://github.com/login/oauth/authorize',
        'token_url' => 'https://github.com/login/oauth/access_token',
        'user_info_url' => 'https://api.github.com/user',
        'scope' => 'user:email'
    ]
];
if (isset($_GET['action']) && $_GET['action'] === 'get_auth_url' && isset($_GET['provider'])) {
    $provider = $_GET['provider'];
    if (!isset($providers[$provider])) exit(json_encode(['error' => 'Unbekannter Provider']));
    $state = bin2hex(random_bytes(8));
    $_SESSION['oauth_state'] = $state;
    $auth_url = $providers[$provider]['auth_url'] . '?' . http_build_query([
        'client_id' => $providers[$provider]['client_id'],
        'redirect_uri' => $providers[$provider]['redirect_uri'],
        'response_type' => 'code',
        'scope' => $providers[$provider]['scope'],
        'state' => $state
    ]);
    exit(json_encode(['url' => $auth_url]));
}
if (isset($_GET['provider'], $_GET['code'])) {
    $provider = $_GET['provider'];
    if (!isset($providers[$provider])) exit('Unbekannter Provider');
    if (!isset($_GET['state'], $_SESSION['oauth_state']) || $_GET['state'] !== $_SESSION['oauth_state']) {
        exit('Ungültiger State');
    }
    unset($_SESSION['oauth_state']);
    $postFields = [
        'client_id' => $providers[$provider]['client_id'],
        'client_secret' => $providers[$provider]['client_secret'],
        'redirect_uri' => $providers[$provider]['redirect_uri'],
        'code' => $_GET['code'],
        'grant_type' => 'authorization_code'
    ];  
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $providers[$provider]['token_url']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postFields));
    if ($provider === 'github') curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json']);
    $response = curl_exec($ch);
    curl_close($ch);
    $token_data = json_decode($response, true);
    if (!isset($token_data['access_token'])) exit('Token konnte nicht abgerufen werden');
    $ch = curl_init();
    $user_info_url = $providers[$provider]['user_info_url'];
    if ($provider === 'facebook') $user_info_url .= '&access_token=' . $token_data['access_token'];
    curl_setopt($ch, CURLOPT_URL, $user_info_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    if ($provider === 'google') curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $token_data['access_token']]);
    if ($provider === 'github') curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: token ' . $token_data['access_token'],
        'User-Agent: PHP-App'
    ]);
    $user = json_decode(curl_exec($ch), true);
    curl_close($ch);   
    echo "<h2>Login erfolgreich über $provider</h2>";
    echo "<pre>" . htmlspecialchars(print_r($user, true)) . "</pre>";
    exit;
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<title>Dreamcodes Social Login</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h2>Social Login</h2>
<button class="social-btn" data-provider="google">Login mit Google</button>
<button class="social-btn" data-provider="facebook">Login mit Facebook</button>
<button class="social-btn" data-provider="github">Login mit GitHub</button>
<script>
$('.social-btn').click(function(){
    var provider = $(this).data('provider');
    $.get('social-login.php', {action: 'get_auth_url', provider: provider}, function(data){
        var result = JSON.parse(data);
        if(result.url){
            window.location.href = result.url;
        } else {
            alert('Fehler beim Abrufen der Login-URL');
        }
    });
});
</script>
</body>
</html>
Dreamcodes Redaktion
Dreamcodes Redaktion
Jeder Inhalt auf Dreamcodes entsteht mit einem klaren Anspruch: geprüfte Praxis statt schneller Theorie. Was hier veröffentlicht wird, basiert auf Best Practices, echten Projekterfahrungen und technischem Verständnis, das über das Offensichtliche hinausgeht. Unser Ziel ist ein Fundament, auf dem du aufbauen kannst, nicht eines, das beim ersten produktiven Einsatz bricht. Wie du die Inhalte integrierst, absicherst und in deinen Kontext überträgst, liegt bei dir. Die fachliche Grundlage liefern wir, die Verantwortung für den Einsatz bleibt deine.

Mehr entdecken? Lass dich von weiteren ähnlichen Inhalten inspirieren!