Skip to content

Commit

Permalink
refactor(pds:auth-verifier): add jwtVerify instance method
Browse files Browse the repository at this point in the history
  • Loading branch information
matthieusieben committed Feb 29, 2024
1 parent 23d2989 commit fdafcc3
Showing 1 changed file with 20 additions and 21 deletions.
41 changes: 20 additions & 21 deletions packages/pds/src/auth-verifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,11 +320,9 @@ export class AuthVerifier {
if (!token) {
throw new AuthRequiredError(undefined, 'AuthMissing')
}
const { payload } = await verifyJwt({
key: this._jwtKey,
token,
verifyOptions,
})

const { payload } = await this.jwtVerify(token, verifyOptions)

const { sub, aud, scope } = payload
if (typeof sub !== 'string' || !sub.startsWith('did:')) {
throw new InvalidRequestError('Malformed token', 'InvalidToken')
Expand Down Expand Up @@ -411,6 +409,23 @@ export class AuthVerifier {
return { iss: payload.iss, aud: payload.aud }
}

protected async jwtVerify(
token: string,
verifyOptions?: jose.JWTVerifyOptions,
) {
try {
return await jose.jwtVerify(token, this._jwtKey, verifyOptions)
} catch (err) {
if (err?.['code'] === 'ERR_JWT_EXPIRED') {
throw new InvalidRequestError('Token has expired', 'ExpiredToken')
}
throw new InvalidRequestError(
'Token could not be verified',
'InvalidToken',
)
}
}

parseRoleCreds(req: express.Request) {
const parsed = parseBasicAuth(req.headers.authorization || '')
const { Missing, Valid, Invalid } = RoleStatus
Expand Down Expand Up @@ -471,22 +486,6 @@ const bearerTokenFromReq = (req: express.Request) => {
return type === BEARER ? token : null
}

const verifyJwt = async (params: {
key: KeyObject
token: string
verifyOptions?: jose.JWTVerifyOptions
}) => {
const { key, token, verifyOptions } = params
try {
return await jose.jwtVerify(token, key, verifyOptions)
} catch (err) {
if (err?.['code'] === 'ERR_JWT_EXPIRED') {
throw new InvalidRequestError('Token has expired', 'ExpiredToken')
}
throw new InvalidRequestError('Token could not be verified', 'InvalidToken')
}
}

export const parseBasicAuth = (
token: string,
): { username: string; password: string } | null => {
Expand Down

0 comments on commit fdafcc3

Please sign in to comment.