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

FR-17861: fix cookie same site policy #366

Closed
wants to merge 1 commit into from
Closed
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
4 changes: 3 additions & 1 deletion packages/nextjs/src/edge/getSessionOnEdge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { NextResponse } from 'next/server';
import config from '../config';
import JwtManager from '../utils/jwt';
import encryptionUtils from '../utils/encryption-edge';
import Cookies from '../utils/cookies';
import { extractSameSiteFromRefreshTokenCookie } from '../utils/refreshAccessTokenIfNeeded/helpers';

async function createSessionFromAccessTokenEdge(data: any): Promise<[string, any, string] | []> {
const accessToken = data.accessToken ?? data.access_token;
Expand Down Expand Up @@ -57,7 +57,9 @@ export const handleHostedLoginCallback = async (
value: session,
expires: new Date(decodedJwt.exp * 1000),
secure: isSecured,
sameSite: extractSameSiteFromRefreshTokenCookie(response.headers.get('set-cookie')?.split(',') ?? []),
});

const refreshCookie = CookieManager.create({
cookieName: `fe_refresh_${config.clientId.replace('-', '')}`,
value: refreshToken ?? '',
Expand Down
3 changes: 2 additions & 1 deletion packages/nextjs/src/middleware/ProxyResponseCallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
removeJwtSignatureFrom,
} from './helpers';
import fronteggLogger from '../utils/fronteggLogger';
import { isSSOPostRequest } from '../utils/refreshAccessTokenIfNeeded/helpers';
import { extractSameSiteFromRefreshTokenCookie, isSSOPostRequest } from '../utils/refreshAccessTokenIfNeeded/helpers';

const logger = fronteggLogger.child({ tag: 'FronteggApiMiddleware.ProxyResponseCallback' });
/**
Expand Down Expand Up @@ -74,6 +74,7 @@ const ProxyResponseCallback: ProxyResCallback<IncomingMessage, NextApiResponse>
expires: new Date(decodedJwt.exp * 1000),
secure: isSecured,
req,
sameSite: extractSameSiteFromRefreshTokenCookie(cookies),
});
cookies.push(...sessionCookie);
}
Expand Down
4 changes: 4 additions & 0 deletions packages/nextjs/src/utils/cookies/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ class CookieManager {
serializeOptions.sameSite = 'none';
}

if (options.sameSite) {
serializeOptions.sameSite = options.sameSite;
}

const serializedCookie = cookieSerializer.serialize(cookieName, cookieValue, serializeOptions);

let newCookies: string[] = [];
Expand Down
2 changes: 1 addition & 1 deletion packages/nextjs/src/utils/cookies/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { IncomingMessage, ServerResponse } from 'http';
export type RequestType = IncomingMessage | Request;
export type ResponseType = ServerResponse;

export interface CreateCookieOptions extends Pick<CookieSerializeOptions, 'domain' | 'httpOnly' | 'path'> {
export interface CreateCookieOptions extends Pick<CookieSerializeOptions, 'domain' | 'httpOnly' | 'path' | 'sameSite'> {
cookieName?: string;
value: string;
secure: boolean;
Expand Down
15 changes: 15 additions & 0 deletions packages/nextjs/src/utils/refreshAccessTokenIfNeeded/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import api from '../../api';
import { getTokensFromCookie } from '../../common';
import { IncomingMessage } from 'http';
import config from '../../config';
import { CookieSerializeOptions } from '../cookies/types';

export function hasRefreshTokenCookie(cookies: Record<string, any>): boolean {
const logger = fronteggLogger.child({ tag: 'refreshToken.hasRefreshTokenCookie' });
Expand Down Expand Up @@ -95,3 +96,17 @@ export function isSamlCallback(url: string): boolean {
export function isSSOPostRequest(url: string): boolean {
return url === '/frontegg/auth/saml/callback' || url === '/frontegg/auth/oidc/callback';
}

export function extractSameSiteFromRefreshTokenCookie(cookies: string[]): CookieSerializeOptions['sameSite'] | undefined {
const refreshTokenKey = CookieManager.refreshTokenKey;
const refreshTokenCookie = cookies.find((cookie) => {
return cookie.replace(/-/g, '') === refreshTokenKey;
});

if (!refreshTokenCookie) {
return undefined;
}

const sameSite = refreshTokenCookie.split(';').find((c: string) => c.trim().toLowerCase().startsWith('samesite'));
return sameSite?.split('=')[1]?.trim() as CookieSerializeOptions['sameSite'];
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { createSessionFromAccessToken } from '../../common';
import config from '../../config';
import CookieManager from '../cookies';
import {
extractSameSiteFromRefreshTokenCookie,
isOauthCallback,
isRuntimeNextRequest,
isSamlCallback,
Expand Down Expand Up @@ -89,6 +90,7 @@ export default async function refreshAccessTokenIfNeeded(ctx: NextPageContext):
expires: new Date(decodedJwt.exp * 1000),
secure: isSecured,
req: nextJsRequest,
sameSite: extractSameSiteFromRefreshTokenCookie(newSetCookie),
});
newSetCookie.push(...cookieValue);
ctx.res?.setHeader('set-cookie', newSetCookie);
Expand Down
Loading