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

fix: create jwt verifier once #13825

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
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
9 changes: 9 additions & 0 deletions packages/adapter-nextjs/src/types/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import { CognitoJwtVerifier } from 'aws-jwt-verify';

export { NextServer } from './NextServer';

export type JwtVerifier = ReturnType<typeof CognitoJwtVerifier.create>;

export interface TokenVerifierMap {
id?: JwtVerifier;
access?: JwtVerifier;
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ export const createRunWithAmplifyServerContext = ({
}: {
config: ResourcesConfig;
}) => {
let tokenValidator: ReturnType<typeof createTokenValidator>;
if (resourcesConfig?.Auth) {
tokenValidator = createTokenValidator({
userPoolId: resourcesConfig?.Auth.Cognito?.userPoolId,
userPoolClientId: resourcesConfig?.Auth.Cognito?.userPoolClientId,
});
}

const runWithAmplifyServerContext: NextServer.RunOperationWithContext =
async ({ nextServerContext, operation }) => {
// When the Auth config is presented, attempt to create a Amplify server
Expand All @@ -35,11 +43,7 @@ export const createRunWithAmplifyServerContext = ({
createCookieStorageAdapterFromNextServerContext(
nextServerContext,
),
createTokenValidator({
userPoolId: resourcesConfig?.Auth.Cognito?.userPoolId,
userPoolClientId:
resourcesConfig?.Auth.Cognito?.userPoolClientId,
}),
tokenValidator,
);
const credentialsProvider = createAWSCredentialsAndIdentityIdProvider(
resourcesConfig.Auth,
Expand Down
30 changes: 23 additions & 7 deletions packages/adapter-nextjs/src/utils/createTokenValidator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,53 @@
// SPDX-License-Identifier: Apache-2.0

import { KeyValueStorageMethodValidator } from '@aws-amplify/core/internals/adapter-core';
import { CognitoJwtVerifier } from 'aws-jwt-verify';

import { TokenVerifierMap } from '../types';

import { isValidCognitoToken } from './isValidCognitoToken';

interface CreateTokenValidatorInput {
userPoolId?: string;
userPoolClientId?: string;
}

/**
* Creates a validator object for validating methods in a KeyValueStorage.
*/
export const createTokenValidator = ({
userPoolId,
userPoolClientId: clientId,
}: CreateTokenValidatorInput): KeyValueStorageMethodValidator => {
const verifierMap: TokenVerifierMap = {};
if (userPoolId && clientId) {
verifierMap.id = CognitoJwtVerifier.create({
userPoolId,
tokenUse: 'id',
clientId,
});
verifierMap.access = CognitoJwtVerifier.create({
userPoolId,
tokenUse: 'access',
clientId,
});
}

return {
// validate access, id tokens
getItem: async (key: string, value: string): Promise<boolean> => {
const tokenType = key.includes('.accessToken')
? 'access'
const verifier = key.includes('.accessToken')
? verifierMap.access
: key.includes('.idToken')
? 'id'
? verifierMap.id
: null;
if (!tokenType) return true;

if (!verifier) return true;
if (!userPoolId || !clientId) return false;

return isValidCognitoToken({
clientId,
userPoolId,
tokenType,
token: value,
verifier,
});
},
};
Expand Down
14 changes: 4 additions & 10 deletions packages/adapter-nextjs/src/utils/isValidCognitoToken.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import { CognitoJwtVerifier } from 'aws-jwt-verify';
import { JwtExpiredError } from 'aws-jwt-verify/error';

import { JwtVerifier } from '../types';

/**
* Verifies a Cognito JWT token for its validity.
*
Expand All @@ -15,18 +16,11 @@ import { JwtExpiredError } from 'aws-jwt-verify/error';
*/
export const isValidCognitoToken = async (input: {
token: string;
userPoolId: string;
clientId: string;
tokenType: 'id' | 'access';
verifier: JwtVerifier;
}): Promise<boolean> => {
const { userPoolId, clientId, tokenType, token } = input;
const { token, verifier } = input;

try {
const verifier = CognitoJwtVerifier.create({
userPoolId,
tokenUse: tokenType,
clientId,
});
await verifier.verify(token);

return true;
Expand Down
Loading