Skip to content
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: Refresh token in authenticateAd route #2001

Merged
merged 1 commit into from
Oct 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions api/src/authenticationUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import * as jsonwebtoken from "jsonwebtoken";

import { JwtConfig } from "./config";

export const refreshTokenExpirationInDays = 8;
export const accessTokenExpirationInMinutesWithrefreshToken = 10;

/**
* Creates a refresh JWT Token
*
* @param userId the current user ID
* @returns a string containing the encoded JWT token
*/
export function createRefreshJWTToken(
payload: {},
key: string,
algorithm: JwtConfig["algorithm"] = "HS256",
): string {
const secretOrPrivateKey = algorithm === "RS256" ? Buffer.from(key, "base64") : key;
return jsonwebtoken.sign(payload, secretOrPrivateKey, {
expiresIn: `${refreshTokenExpirationInDays}d`,
algorithm,
});
}
2 changes: 2 additions & 0 deletions api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,8 @@ if (authProxy.enabled) {
),
getGroupsForUser: (ctx, serviceUser, userId) =>
GroupQueryService.getGroupsForUser(db, ctx, serviceUser, userId),
storeRefreshToken: async (userId, refreshToken, validUntil) =>
dbConnection?.insertRefreshToken(userId, refreshToken, validUntil),
},
jwt,
);
Expand Down
25 changes: 5 additions & 20 deletions api/src/user_authenticate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ import Joi = require("joi");
import * as jsonwebtoken from "jsonwebtoken";
import { VError } from "verror";

import {
accessTokenExpirationInMinutesWithrefreshToken,
createRefreshJWTToken,
refreshTokenExpirationInDays,
} from "./authenticationUtils";
import { JwtConfig, config } from "./config";
import { toHttpError } from "./http_errors";
import { assertUnreachable } from "./lib/assertUnreachable";
Expand All @@ -15,8 +20,6 @@ import { Group } from "./service/domain/organization/group";
import { ServiceUser } from "./service/domain/organization/service_user";

export const MAX_GROUPS_LENGTH = 3000;
export const accessTokenExpirationInMinutesWithrefreshToken = 10;
export const refreshTokenExpirationInDays = 8;

/**
* Represents the request body of the endpoint
Expand Down Expand Up @@ -364,21 +367,3 @@ function createJWT(
{ expiresIn, algorithm },
);
}

/**
* Creates a refresh JWT Token
*
* @param userId the current user ID
* @returns a string containing the encoded JWT token
*/
function createRefreshJWTToken(
payload: {},
key: string,
algorithm: JwtConfig["algorithm"] = "HS256",
): string {
const secretOrPrivateKey = algorithm === "RS256" ? Buffer.from(key, "base64") : key;
return jsonwebtoken.sign(payload, secretOrPrivateKey, {
expiresIn: `${refreshTokenExpirationInDays}d`,
algorithm,
});
}
64 changes: 63 additions & 1 deletion api/src/user_authenticateAd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,16 @@ import Joi = require("joi");
import * as jsonwebtoken from "jsonwebtoken";
import { VError } from "verror";

import {
accessTokenExpirationInMinutesWithrefreshToken,
createRefreshJWTToken,
refreshTokenExpirationInDays,
} from "./authenticationUtils";
import { JwtConfig, config } from "./config";
import { toHttpError } from "./http_errors";
import { assertUnreachable } from "./lib/assertUnreachable";
import { Ctx } from "./lib/ctx";
import { saveValue } from "./lib/keyValueStore";
import * as Result from "./result";
import { AuthToken } from "./service/domain/organization/auth_token";
import { Group } from "./service/domain/organization/group";
Expand Down Expand Up @@ -45,6 +51,14 @@ function validateRequestBody(body: unknown): Result.Type<RequestBody> {
return !error ? value : error;
}

interface RequestResponse {
apiVersion: string;
data: {
user: LoginResponse;
accessTokenExp?: number;
};
}

interface LoginResponse {
id: string;
displayName: string;
Expand Down Expand Up @@ -169,6 +183,7 @@ interface Service {
serviceUser: ServiceUser,
userId: string,
): Promise<Result.Type<Group[]>>;
storeRefreshToken(userId: string, refreshToken: string, validUntil: number): Promise<void>;
}

/**
Expand Down Expand Up @@ -228,6 +243,34 @@ export function addHttpHandler(
const token = tokenResult;
const signedJwt = createJWTWithMeta(token, jwt.secretOrPrivateKey, jwt.algorithm);

// store refresh token
const now = new Date();
// time in miliseconds of refresh token expiration
const refreshTokenExpiration = new Date(
now.getTime() + 1000 * 60 * 60 * 24 * refreshTokenExpirationInDays,
);
const refreshToken = createRefreshJWTToken(
{ userId: token.userId, expirationAt: refreshTokenExpiration },
jwt.secretOrPrivateKey,
jwt.algorithm as "HS256" | "RS256",
);

if (config.refreshTokenStorage === "memory") {
saveValue(
`refreshToken.${refreshToken}`,
{
userId: token.userId,
},
refreshTokenExpiration,
);
} else if (config.refreshTokenStorage === "db") {
await service.storeRefreshToken(
token.userId,
refreshToken,
refreshTokenExpiration.getTime(),
);
}

const groupsResult = await service.getGroupsForUser(
ctx,
{ id: token.userId, groups: token.groups, address: token.address },
Expand All @@ -246,19 +289,38 @@ export function addHttpHandler(
groups: groups.map((x) => ({ groupId: x.id, displayName: x.displayName })),
token: signedJwt,
};
const body = {

const body: RequestResponse = {
apiVersion: "1.0",
data: {
user: loginResponse,
},
};

// conditionally add token expiration to payload
if (config.refreshTokenStorage && ["db", "memory"].includes(config.refreshTokenStorage)) {
body.data.accessTokenExp = 1000 * 60 * accessTokenExpirationInMinutesWithrefreshToken;
}

reply
.setCookie("token", signedJwt, {
path: "/",
secure: config.secureCookie,
httpOnly: true,
sameSite: true,
})
.setCookie("refreshToken", refreshToken, {
path: "/api/user.refreshtoken",
secure: config.secureCookie,
httpOnly: true,
sameSite: "strict",
})
.setCookie("refreshToken", refreshToken, {
path: "/api/user.logout",
secure: config.secureCookie,
httpOnly: true,
sameSite: "strict",
})
.status(200)
.send(body);
} catch (err) {
Expand Down
6 changes: 2 additions & 4 deletions api/src/user_refreshToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import Joi = require("joi");
import * as jsonwebtoken from "jsonwebtoken";
import { VError } from "verror";

import { accessTokenExpirationInMinutesWithrefreshToken } from "./authenticationUtils";
import { JwtConfig, config } from "./config";
import { toHttpError } from "./http_errors";
import { AuthenticatedRequest } from "./httpd/lib";
Expand All @@ -12,10 +13,7 @@ import { AuthToken } from "./service/domain/organization/auth_token";
import { Group } from "./service/domain/organization/group";
import { ServiceUser } from "./service/domain/organization/service_user";
import { AugmentedFastifyInstance } from "./types";
import {
MAX_GROUPS_LENGTH,
accessTokenExpirationInMinutesWithrefreshToken,
} from "./user_authenticate";
import { MAX_GROUPS_LENGTH } from "./user_authenticate";

/**
* Represents the request body of the endpoint
Expand Down
Loading