Skip to content

Commit

Permalink
fix bugs with Microsoft auth on local
Browse files Browse the repository at this point in the history
  • Loading branch information
freemvmt committed Jul 17, 2024
1 parent 472e8f5 commit b0307d4
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 17 deletions.
2 changes: 2 additions & 0 deletions api.planx.uk/modules/auth/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,13 +124,15 @@ export const useGoogleCallbackAuth: RequestHandler = (req, res, next) => {
};

export const useMicrosoftAuth: RequestHandler = (req, res, next) => {
console.log("INVOKING MICROSOFT MIDDLEWARE")
req.session!.returnTo = req.get("Referrer");
return passport.authenticate("microsoft-oidc", {
prompt: "select_account",
})(req, res, next);
};

export const useMicrosoftCallbackAuth: RequestHandler = (req, res, next) => {
console.log("INVOKING MICROSOFT CALLBACK MIDDLEWARE")
return passport.authenticate("microsoft-oidc", {
failureRedirect: "/auth/login/failed",
})(req, res, next);
Expand Down
2 changes: 1 addition & 1 deletion api.planx.uk/modules/auth/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ router.get(
Controller.handleSuccess,
);
router.get("/auth/microsoft", Middleware.useMicrosoftAuth)
router.get(
router.post(
"/auth/microsoft/callback",
Middleware.useMicrosoftCallbackAuth,
Controller.handleSuccess,
Expand Down
55 changes: 39 additions & 16 deletions api.planx.uk/modules/auth/strategy/microsoft-oidc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,38 +23,59 @@ export const getMicrosoftOidcStrategy = (
console.log("redirect uri domain:");
console.log(process.env.API_URL_EXT);

const client_id = process.env.MICROSOFT_CLIENT_ID!;
if (typeof client_id !== 'string') {
throw new Error('No MICROSOFT_CLIENT_ID in the environment');
}

const microsoftClient = new microsoftIssuer.Client({
client_id: process.env.MICROSOFT_CLIENT_ID!,
client_id: client_id,
client_secret: process.env.MICROSOFT_CLIENT_SECRET!,
redirect_uris: [`${process.env.API_URL_EXT}/auth/microsoft/callback`],
post_logout_redirect_uris: [`${process.env.API_URL_EXT}/logout`],
response_types: ["id_token"],
});

// should nonce be generated here, or in middleware functions?
const nonce = generators.nonce();
console.log(`Generated a nonce: ${nonce}`);
// TODO: store nonce (encrypted and httpOnly) in session

microsoftClient.authorizationUrl({
scope: "openid email profile",
response_mode: "form_post", // could also be 'query' or 'fragment'
nonce,
});

console.log("Built Microsoft client:");
console.log(microsoftClient.metadata);

// oidc = Open ID Connect
return new Strategy(
{ client: microsoftClient },
async (tokenset: TokenSet, userInfo: any, done: any): Promise<void> => {
console.log("USER INFO:");
console.log(userInfo);

return new Strategy({
client: microsoftClient,
params: {
scope: "openid email profile",
response_mode: "form_post", // could also be 'query' or 'fragment'
nonce,
},
passReqToCallback: true,
// usePKCE: false, // whether to use PKCE - defaults to true, according to docs
},
async (req: any, tokenSet: TokenSet, done: any): Promise<void> => {
console.log("INVOKING STRATEGY CALLBACK!")

console.log("TOKEN SET:");
console.log(tokenset);
console.log(tokenSet);

console.log("ID TOKEN:")
console.log(tokenSet.id_token)

console.log("CLAIMS:")
console.log(tokenSet.claims())

const id_token = tokenSet.id_token;
const state = tokenSet.state;
// TODO: do something with state??

const claims = tokenSet.claims();
const email = claims.email
const returned_nonce = claims.nonce
// TODO: compare nonces

const email = "xxx";
if (!email) throw Error("Unable to authenticate without email");

const jwt = await buildJWT(email);
Expand All @@ -66,7 +87,9 @@ export const getMicrosoftOidcStrategy = (
} as any);
}

done(null, { jwt });
return done(null, { jwt });

// TODO: handle error case i.e. done(err)
},
);
};
1 change: 1 addition & 0 deletions api.planx.uk/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ app.use(
// we have to fetch the Microsoft OpenID issuer to pass to our strategy constructor
// TODO: handle failure to fetch issuer
getMicrosoftIssuer().then((microsoftIssuer: Issuer) => {
console.log("GOT MS ISSUER - SETTING UP STRATEGY")
passport.use("microsoft-oidc", getMicrosoftOidcStrategy(microsoftIssuer));
});
passport.use("google", googleStrategy);
Expand Down
3 changes: 3 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,9 @@ services:
UNIFORM_CLIENT_AYLESBURY_VALE: ${UNIFORM_CLIENT_AYLESBURY_VALE}
UNIFORM_CLIENT_CHILTERN: ${UNIFORM_CLIENT_CHILTERN}
UNIFORM_CLIENT_WYCOMBE: ${UNIFORM_CLIENT_WYCOMBE}
# microsoft-oidc strategy testing
MICROSOFT_CLIENT_ID: ${MICROSOFT_CLIENT_ID}
MICROSOFT_CLIENT_SECRET: ${MICROSOFT_CLIENT_SECRET}

sharedb:
restart: unless-stopped
Expand Down

0 comments on commit b0307d4

Please sign in to comment.