-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[api] add Microsoft strategy to auth module (single sign-on) #3453
Changes from 4 commits
0b836c4
ba98e81
1a89b48
a918020
e599a44
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
import { Issuer } from "openid-client"; | ||
import type { Authenticator } from "passport"; | ||
import passport from "passport"; | ||
|
||
import { googleStrategy } from "./strategy/google.js"; | ||
import { | ||
getMicrosoftOidcStrategy, | ||
getMicrosoftClientConfig, | ||
MICROSOFT_OPENID_CONFIG_URL, | ||
} from "./strategy/microsoft-oidc.js"; | ||
|
||
export default async (): Promise<Authenticator> => { | ||
// explicitly instantiate new passport class for clarity | ||
const customPassport = new passport.Passport(); | ||
|
||
// instantiate Microsoft OIDC client, and use it to build the related strategy | ||
const microsoftIssuer = await Issuer.discover(MICROSOFT_OPENID_CONFIG_URL); | ||
console.debug("Discovered issuer %s", microsoftIssuer.issuer); | ||
const microsoftOidcClient = new microsoftIssuer.Client( | ||
getMicrosoftClientConfig(), | ||
); | ||
console.debug("Built Microsoft client: %O", microsoftOidcClient); | ||
customPassport.use( | ||
"microsoft-oidc", | ||
getMicrosoftOidcStrategy(microsoftOidcClient), | ||
); | ||
|
||
// note that we don't serialize the user in any meaningful way - we just store the entire jwt in session | ||
// i.e. req.session.passport.user == { jwt: "..." } | ||
customPassport.use("google", googleStrategy); | ||
customPassport.serializeUser((user: Express.User, done) => { | ||
done(null, user); | ||
}); | ||
customPassport.deserializeUser((user: Express.User, done) => { | ||
done(null, user); | ||
}); | ||
|
||
// tsc dislikes the use of 'this' in the passportjs codebase, so we cast explicitly | ||
return customPassport as Authenticator; | ||
}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,16 +1,26 @@ | ||
import { Router } from "express"; | ||
import type { Authenticator } from "passport"; | ||
import * as Middleware from "./middleware.js"; | ||
import * as Controller from "./controller.js"; | ||
|
||
const router = Router(); | ||
export default (passport: Authenticator): Router => { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We have to pass the |
||
const router = Router(); | ||
|
||
router.get("/logout", Controller.logout); | ||
router.get("/auth/login/failed", Controller.failedLogin); | ||
router.get("/auth/google", Middleware.useGoogleAuth); | ||
router.get( | ||
"/auth/google/callback", | ||
Middleware.useGoogleCallbackAuth, | ||
Controller.handleSuccess, | ||
); | ||
router.get("/logout", Controller.logout); | ||
// router.get("/auth/frontchannel-logout", Controller.frontChannelLogout) | ||
router.get("/auth/login/failed", Controller.failedLogin); | ||
router.get("/auth/google", Middleware.getGoogleAuthHandler(passport)); | ||
|
||
router.get( | ||
"/auth/google/callback", | ||
Middleware.getGoogleCallbackAuthHandler(passport), | ||
|
||
Controller.handleSuccess, | ||
); | ||
router.get("/auth/microsoft", Middleware.getMicrosoftAuthHandler(passport)); | ||
|
||
router.post( | ||
"/auth/microsoft/callback", | ||
Middleware.getMicrosoftCallbackAuthHandler(passport), | ||
|
||
Controller.handleSuccess, | ||
); | ||
|
||
export default router; | ||
return router; | ||
}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
import type { TokenSet, Client, ClientMetadata } from "openid-client"; | ||
import { Strategy } from "openid-client"; | ||
import { buildJWT } from "../service.js"; | ||
|
||
export const MICROSOFT_OPENID_CONFIG_URL = | ||
"https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration"; | ||
|
||
export const getMicrosoftClientConfig = (): ClientMetadata => { | ||
const client_id = process.env.MICROSOFT_CLIENT_ID!; | ||
if (typeof client_id !== "string") { | ||
throw new Error("No MICROSOFT_CLIENT_ID in the environment"); | ||
} | ||
return { | ||
client_id, | ||
client_secret: process.env.MICROSOFT_CLIENT_SECRET!, | ||
redirect_uris: [`${process.env.API_URL_EXT}/auth/microsoft/callback`], | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this has to match one of the redirect URI configured in the PlanX Azure application i.e. |
||
post_logout_redirect_uris: [process.env.EDITOR_URL_EXT!], | ||
response_types: ["id_token"], | ||
}; | ||
}; | ||
|
||
// oidc = OpenID Connect, an auth standard built on top of OAuth 2.0 | ||
export const getMicrosoftOidcStrategy = (client: Client): Strategy<Client> => { | ||
return new Strategy( | ||
{ | ||
client: client, | ||
params: { | ||
scope: "openid email profile", | ||
response_mode: "form_post", | ||
}, | ||
// need the request in the verify callback to validate the returned nonce | ||
passReqToCallback: true, | ||
}, | ||
async (req: any, tokenSet: TokenSet, done: any): Promise<void> => { | ||
Check warning on line 34 in api.planx.uk/modules/auth/strategy/microsoft-oidc.ts GitHub Actions / Run API Tests
|
||
// TODO: use tokenSet.state to pass the redirectTo query param through the auth flow | ||
const claims = tokenSet.claims(); | ||
const email = claims.email; | ||
const returned_nonce = claims.nonce; | ||
|
||
if (returned_nonce != req.session.nonce) { | ||
return done( | ||
new Error("Returned nonce does not match session nonce"), | ||
null, | ||
); | ||
} | ||
|
||
if (!email) { | ||
return done(new Error("Unable to authenticate without email"), null); | ||
} | ||
|
||
const jwt = await buildJWT(email); | ||
|
||
if (!jwt) { | ||
return done( | ||
{ | ||
status: 404, | ||
message: `User (${email}) not found. Do you need to log in to a different Microsoft Account?`, | ||
} as any, | ||
null, | ||
); | ||
} | ||
|
||
return done(null, { jwt }); | ||
}, | ||
); | ||
}; |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -10,15 +10,14 @@ import pinoLogger from "express-pino-logger"; | |
import helmet from "helmet"; | ||
import { Server } from "http"; | ||
import "isomorphic-fetch"; | ||
import passport from "passport"; | ||
import noir from "pino-noir"; | ||
import airbrake from "./airbrake.js"; | ||
import { useSwaggerDocs } from "./docs/index.js"; | ||
import { ServerError } from "./errors/index.js"; | ||
import adminRoutes from "./modules/admin/routes.js"; | ||
import analyticsRoutes from "./modules/analytics/routes.js"; | ||
import authRoutes from "./modules/auth/routes.js"; | ||
import { googleStrategy } from "./modules/auth/strategy/google.js"; | ||
import getPassport from "./modules/auth/passport.js"; | ||
import getAuthRoutes from "./modules/auth/routes.js"; | ||
import fileRoutes from "./modules/file/routes.js"; | ||
import flowRoutes from "./modules/flows/routes.js"; | ||
import gisRoutes from "./modules/gis/routes.js"; | ||
|
@@ -122,19 +121,16 @@ app.use( | |
// register stubs after cookieSession middleware initialisation | ||
app.use(registerSessionStubs); | ||
|
||
passport.use("google", googleStrategy); | ||
|
||
passport.serializeUser(function (user, cb) { | ||
cb(null, user); | ||
}); | ||
|
||
passport.deserializeUser(function (obj: Express.User, cb) { | ||
cb(null, obj); | ||
}); | ||
// equip passport with auth strategies early on, so we can pass it to route handlers | ||
const passport = await getPassport(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. the fabled top-level await! |
||
app.use(passport.initialize()); | ||
app.use(passport.session()); | ||
|
||
app.use(bodyParser.urlencoded({ extended: true })); | ||
|
||
// auth routes rely on the passport class we've just initialised | ||
const authRoutes = await getAuthRoutes(passport); | ||
|
||
// Setup API routes | ||
app.use(adminRoutes); | ||
app.use(analyticsRoutes); | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fetches config from Microsoft's
.well-known
address