feat: set JWT token field name with saveToJWT (#3126)

This commit is contained in:
Dan Ribbens
2023-08-04 13:22:05 -04:00
committed by GitHub
parent 1c15868b50
commit 356f174b9f
7 changed files with 46 additions and 19 deletions

View File

@@ -6,6 +6,10 @@ import { AuthDebug } from './AuthDebug';
export const slug = 'users';
export const namedSaveToJWTValue = 'namedSaveToJWT value';
export const saveToJWTKey = 'x-custom-jwt-property-name';
export default buildConfigWithDefaults({
admin: {
user: 'users',
@@ -38,6 +42,12 @@ export default buildConfigWithDefaults({
saveToJWT: true,
hasMany: true,
},
{
name: 'namedSaveToJWT',
type: 'text',
defaultValue: namedSaveToJWTValue,
saveToJWT: saveToJWTKey,
},
{
name: 'custom',
label: 'Custom',

View File

@@ -1,7 +1,8 @@
import mongoose from 'mongoose';
import jwtDecode from 'jwt-decode';
import payload from '../../src';
import { initPayloadTest } from '../helpers/configHelpers';
import { slug } from './config';
import { namedSaveToJWTValue, saveToJWTKey, slug } from './config';
import { devUser } from '../credentials';
import type { User } from '../../src/auth';
@@ -101,6 +102,24 @@ describe('Auth', () => {
expect(data.user.email).toBeDefined();
});
it('should have fields saved to JWT', async () => {
const {
email: jwtEmail,
collection,
roles,
[saveToJWTKey]: customJWTPropertyKey,
iat,
exp,
} = jwtDecode<User>(token);
expect(jwtEmail).toBeDefined();
expect(collection).toEqual('users');
expect(Array.isArray(roles)).toBeTruthy();
// 'x-custom-jwt-property-name': 'namedSaveToJWT value'
expect(customJWTPropertyKey).toEqual(namedSaveToJWTValue);
expect(iat).toBeDefined();
expect(exp).toBeDefined();
});
it('should allow authentication with an API key with useAPIKey', async () => {
const apiKey = '0123456789ABCDEFGH';