Move auth token to contrib

This commit is contained in:
Erik Larsson
2021-02-20 01:46:00 +01:00
parent 145205a14b
commit 74534a0f8c
5 changed files with 44 additions and 54 deletions
@@ -13,10 +13,33 @@ Caveat: as of writing this, Backstage does not refresh the identity token so eve
import cookieParser from 'cookie-parser';
import { Request, Response, NextFunction } from 'express';
import { JWT } from 'jose';
import { URL } from 'url';
import { IdentityClient } from '@backstage/plugin-auth-backend';
// ...
function setTokenCookie(
res: Response,
options: { token: string; secure: boolean; cookieDomain: string },
) {
try {
const payload = JWT.decode(options.token) as object & {
exp: number;
};
res.cookie(`token`, options.token, {
expires: new Date(payload?.exp ? payload?.exp * 1000 : 0),
secure: options.secure,
sameSite: 'lax',
domain: options.cookieDomain,
path: '/',
httpOnly: true,
});
} catch (_err) {
// Ignore
}
}
async function main() {
// ...
@@ -25,6 +48,9 @@ async function main() {
discovery,
issuer: await discovery.getExternalBaseUrl('auth'),
});
const baseUrl = config.getString('backend.baseUrl');
const secure = baseUrl.startsWith('https://');
const cookieDomain = new URL(baseUrl).hostname;
const authMiddleware = async (
req: Request,
res: Response,
@@ -33,8 +59,19 @@ async function main() {
try {
const token =
IdentityClient.getBearerToken(req.headers.authorization) ||
req.cookies['access-token'];
req.cookies['token'];
req.user = await identity.authenticate(token);
if (!req.headers.authorization) {
// Authorization header may be forwarded by plugin requests
req.headers.authorization = `Bearer ${token}`;
}
if (token !== req.cookies['token']) {
setTokenCookie(res, {
token,
secure,
cookieDomain,
});
}
next();
} catch (error) {
res.status(401).send(`Unauthorized`);