azure-ad-auth-kit
Version:
Microsoft Azure AD Auth Kit (OAuth2 login, no config)
86 lines (69 loc) • 2.95 kB
JavaScript
const express = require("express");
const cors = require("cors");
const jwt = require("jsonwebtoken");
const { getAccessTokenAndProfile } = require("../lib/azureAdAuth");
const app = express();
const PORT = 3000;
// Replace with your own secure config
const config = {
TENANT_ID: "your-tenant-id",
CLIENT_ID: "your-client-id",
CLIENT_SECRET: "your-client-secret",
REDIRECT_URI: "http://localhost:3000/redirect",
JWT_SECRET: "your-super-secret",
FRONTEND_DASHBOARD_URL: "http://localhost:5173/dashboard"
};
app.use(cors({ origin: true, credentials: true }));
app.get("/login", (req, res) => {
const authUrl = `https://login.microsoftonline.com/${config.TENANT_ID}/oauth2/v2.0/authorize?client_id=${config.CLIENT_ID}&response_type=code&redirect_uri=${encodeURIComponent(
config.REDIRECT_URI
)}&response_mode=query&scope=openid profile email offline_access https://graph.microsoft.com/User.Read&state=manual`;
res.redirect(authUrl);
});
app.get("/silent-login", (req, res) => {
const authUrl = `https://login.microsoftonline.com/${config.TENANT_ID}/oauth2/v2.0/authorize?client_id=${config.CLIENT_ID}&response_type=code&redirect_uri=${encodeURIComponent(
config.REDIRECT_URI
)}&response_mode=query&scope=openid profile email offline_access https://graph.microsoft.com/User.Read&prompt=none&state=sso`;
res.redirect(authUrl);
});
app.get("/redirect", async (req, res) => {
const { code, state } = req.query;
if (!code) return res.status(400).json({ error: "Missing code." });
try {
const { userInfo, graphToken } = await getAccessTokenAndProfile(code, config);
const jwtPayload = {
email: userInfo.mail || userInfo.userPrincipalName,
name: userInfo.displayName,
id: userInfo.id
};
const token = jwt.sign(jwtPayload, config.JWT_SECRET, { expiresIn: "6h" });
res.json({
message: "✅ Login Successful",
from: state === "sso" ? "SSO" : "OAuth",
token: token,
graphToken: graphToken,
user: jwtPayload
});
} catch (err) {
console.error("❌ Redirect Error:", err.message);
res.status(500).send("Redirect failed.");
}
});
app.get("/profile", async (req, res) => {
const authHeader = req.headers.authorization;
const graphToken = req.headers.graphtoken;
if (!authHeader || !graphToken) return res.status(401).json({ error: "Missing token(s)." });
try {
const decoded = jwt.verify(authHeader.replace("Bearer ", ""), config.JWT_SECRET);
const { getUserProfile } = require("../lib/azureAdAuth");
const profile = await getUserProfile(graphToken);
res.json({ user: decoded, profile });
} catch (err) {
res.status(403).json({ error: "Unauthorized." });
}
});
app.listen(PORT, () => {
console.log(`✅ API running at http://localhost:${PORT}`);
console.log("🔐 OAuth Login:", `http://localhost:${PORT}/login`);
console.log("🧠 SSO Login: ", `http://localhost:${PORT}/silent-login`);
});