OpenID Connect is a simple identity layer on top of the OAuth 2.0 protocol. It allows applications to verify the identity of users based on the authentication performed by an authorization server. This protocol is commonly used for single sign-on (SSO) applications, enabling seamless access across multiple services. Below are three diverse, practical examples of OpenID Connect authentication that illustrate its usage in different contexts.
This example demonstrates how a web application can implement OpenID Connect for user login, allowing users to authenticate using their Google account.
To set up OpenID Connect, the application must register with Google to obtain client credentials (Client ID and Client Secret).
const express = require('express');
const request = require('request');
const querystring = require('querystring');
const app = express();
const CLIENT_ID = 'YOUR_CLIENT_ID';
const CLIENT_SECRET = 'YOUR_CLIENT_SECRET';
const REDIRECT_URI = 'http://localhost:3000/callback';
const AUTHORIZATION_URL = 'https://accounts.google.com/o/oauth2/auth';
const TOKEN_URL = 'https://oauth2.googleapis.com/token';
app.get('/login', (req, res) => {
const authUrl = `${AUTHORIZATION_URL}?${querystring.stringify({
client_id: CLIENT_ID,
redirect_uri: REDIRECT_URI,
response_type: 'code',
scope: 'openid email profile'
})}`;
res.redirect(authUrl);
});
app.get('/callback', (req, res) => {
const { code } = req.query;
request.post({
url: TOKEN_URL,
form: {
code,
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
redirect_uri: REDIRECT_URI,
grant_type: 'authorization_code'
}
}, (err, httpResponse, body) => {
const tokens = JSON.parse(body);
// Now you can use the tokens to access user information
res.json(tokens);
});
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
passport-openidconnect
for easier implementation.In this scenario, a mobile application uses OpenID Connect to authenticate users via an identity provider (IDP) like Auth0. This method allows users to log in securely with their existing accounts.
import UIKit
import AuthenticationServices
class LoginViewController: UIViewController {
func login() {
let authURL = URL(string: "https://YOUR_IDP_DOMAIN/authorize?client_id=YOUR_CLIENT_ID&response_type=id_token&scope=openid profile&redirect_uri=YOUR_REDIRECT_URI")!
let session = ASWebAuthenticationSession(url: authURL, callbackURLScheme: "YOUR_CALLBACK_SCHEME") { callbackURL, error in
if let error = error {
print("Error: \(error.localizedDescription)")
return
}
guard let callbackURL = callbackURL,
let components = URLComponents(url: callbackURL, resolvingAgainstBaseURL: false),
let idToken = components.queryItems?.first(where: { $0.name == "id_token" })?.value else {
return
}
// Use the ID token for authentication
print("ID Token: \(idToken)")
}
session.start()
}
}
This example illustrates how an IoT device can authenticate to a server using OpenID Connect. This is useful for devices that require secure access to cloud services.
import requests
CLIENT_ID = 'YOUR_CLIENT_ID'
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
TOKEN_URL = 'https://YOUR_AUTH_SERVER/token'
def authenticate_device():
response = requests.post(TOKEN_URL, data={
'grant_type': 'client_credentials',
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET
})
if response.status_code == 200:
tokens = response.json()
print(f'Tokens: {tokens}')
else:
print('Authentication failed')
if __name__ == '__main__':
authenticate_device()
By understanding these examples of OpenID Connect authentication, developers can effectively implement secure user authentication across various applications and devices.