feat: Improve auth middlewares (#4485)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* chore: added option to override wwwAuthenticateHeader * chore: added option to pass function * chore: formatted code * chore: minor change * chore: minor change * feat: added common patterns in jwk middleware * chore: changed the types * chore: changed the var name * chore: resolved jwk tests issues * chore: did the same in jwt middleware * chore: resolved the tests * chore: minor change * chore: added as string * chore: formatted the file * chore: resolved tests issues * chore: improvements * chore: formatted the code * chore: updated JS Docs * chore: removed the jwk and jwt changes * chore: added back props for backward compatibilty * ci: apply automated fixes * fix the jsdoc and add space after comma in WWW-Authenticate header object * Revert "fix the jsdoc and add space after comma in WWW-Authenticate header object" This reverts commit 3f6f4461e758237663eb8bb33ac2cfd8f0b25b7a. * fix the jsdoc ---------
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
- Co-authored-by: Yusuke Wada <yusuke@kamawada.com>
Diff stats
2 files+458 added−34 removed
- tests:+399 added−23 removed
- other:+59 added−11 removed
Provenance
- Commit
96d2a89- Tree
9c6e578- Author
Aditya Mathur <57684218+MathurAditya724@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
279184b
2 files changed+458 added−34 removed
modified:src/middleware/bearer-auth/index.test.ts+399 added-23 removed
68 unmodified lines69 return c.text('auth-custom-header')70 })71 72 app.use(73+ '/auth-custom-no-authentication-header-wwwAuthenticateHeader-string/*',74+ bearerAuth({75+ token: tokens,76+ noAuthenticationHeader: {77+ wwwAuthenticateHeader: 'Bearer error="Unauthorized",error_description="Unauthorized"',78+ },79+ })80+ )81+ app.get('/auth-custom-no-authentication-header-wwwAuthenticateHeader-string/*', (c) => {82+ handlerExecuted = true83+ return c.text('auth')84+ })85+86+ app.use(87+ '/auth-custom-no-authentication-header-wwwAuthenticateHeader-object/*',88+ bearerAuth({89+ token: tokens,90+ noAuthenticationHeader: {91+ wwwAuthenticateHeader: {92+ error: 'Unauthorized',93+ error_description: 'Unauthorized',94+ },95+ },96+ })97+ )98+ app.get('/auth-custom-no-authentication-header-wwwAuthenticateHeader-object/*', (c) => {99+ handlerExecuted = true100+ return c.text('auth')101+ })102+103+ app.use(104+ '/auth-custom-no-authentication-header-wwwAuthenticateHeader-function-string/*',105+ bearerAuth({106+ token: tokens,107+ noAuthenticationHeader: {108+ wwwAuthenticateHeader: () =>109+ 'Bearer error="Unauthorized",error_description="Unauthorized"',110+ },111+ })112+ )113+ app.get(114+ '/auth-custom-no-authentication-header-wwwAuthenticateHeader-function-string/*',115+ (c) => {116+ handlerExecuted = true117+ return c.text('auth')118+ }119+ )120+121+ app.use(122+ '/auth-custom-no-authentication-header-wwwAuthenticateHeader-function-object/*',123+ bearerAuth({124+ token: tokens,125+ noAuthenticationHeader: {126+ wwwAuthenticateHeader: () => ({127+ error: 'Unauthorized',128+ error_description: 'Unauthorized',129+ }),130+ },131+ })132+ )133+ app.get(134+ '/auth-custom-no-authentication-header-wwwAuthenticateHeader-function-object/*',135+ (c) => {136+ handlerExecuted = true137+ return c.text('auth')138+ }139+ )140+141+ app.use(142 '/auth-custom-no-authentication-header-message-string/*',143 bearerAuth({144 token,76- noAuthenticationHeaderMessage: 'Custom no authentication header message as string',145+ noAuthenticationHeader: { message: 'Custom no authentication header message as string' },146 })147 )148 app.get('/auth-custom-no-authentication-header-message-string/*', (c) => {149 handlerExecuted = true3 unmodified lines153 app.use(154 '/auth-custom-no-authentication-header-message-object/*',155 bearerAuth({156 token,88- noAuthenticationHeaderMessage: {89- message: 'Custom no authentication header message as object',157+ noAuthenticationHeader: {158+ message: { message: 'Custom no authentication header message as object' },159 },160 })161 )162 app.get('/auth-custom-no-authentication-header-message-object/*', (c) => {4 unmodified lines167 app.use(168 '/auth-custom-no-authentication-header-message-function-string/*',169 bearerAuth({170 token,102- noAuthenticationHeaderMessage: () =>103- 'Custom no authentication header message as function string',171+ noAuthenticationHeader: {172+ message: () => 'Custom no authentication header message as function string',173+ },174 })175 )176 app.get('/auth-custom-no-authentication-header-message-function-string/*', (c) => {177 handlerExecuted = true3 unmodified lines181 app.use(182 '/auth-custom-no-authentication-header-message-function-object/*',183 bearerAuth({184 token,185+ noAuthenticationHeader: {115- noAuthenticationHeaderMessage: () => ({116- message: 'Custom no authentication header message as function object',117- }),186+ message: () => ({187+ message: 'Custom no authentication header message as function object',188+ }),189+ },190 })191 )192 app.get('/auth-custom-no-authentication-header-message-function-object/*', (c) => {193 handlerExecuted = true194 return c.text('auth')195 })196 197 app.use(198+ '/auth-custom-invalid-authentication-header-wwwAuthenticateHeader-string/*',199+ bearerAuth({200+ token: tokens,201+ invalidAuthenticationHeader: {202+ wwwAuthenticateHeader: 'Bearer error="Unauthorized",error_description="Unauthorized"',203+ },204+ })205+ )206+ app.get('/auth-custom-invalid-authentication-header-wwwAuthenticateHeader-string/*', (c) => {207+ handlerExecuted = true208+ return c.text('auth')209+ })210+211+ app.use(212+ '/auth-custom-invalid-authentication-header-wwwAuthenticateHeader-object/*',213+ bearerAuth({214+ token: tokens,215+ invalidAuthenticationHeader: {216+ wwwAuthenticateHeader: {217+ error: 'Unauthorized',218+ error_description: 'Unauthorized',219+ },220+ },221+ })222+ )223+ app.get('/auth-custom-invalid-authentication-header-wwwAuthenticateHeader-object/*', (c) => {224+ handlerExecuted = true225+ return c.text('auth')226+ })227+228+ app.use(229+ '/auth-custom-invalid-authentication-header-wwwAuthenticateHeader-function-string/*',230+ bearerAuth({231+ token: tokens,232+ invalidAuthenticationHeader: {233+ wwwAuthenticateHeader: () =>234+ 'Bearer error="Unauthorized",error_description="Unauthorized"',235+ },236+ })237+ )238+ app.get(239+ '/auth-custom-invalid-authentication-header-wwwAuthenticateHeader-function-string/*',240+ (c) => {241+ handlerExecuted = true242+ return c.text('auth')243+ }244+ )245+246+ app.use(247+ '/auth-custom-invalid-authentication-header-wwwAuthenticateHeader-function-object/*',248+ bearerAuth({249+ token: tokens,250+ invalidAuthenticationHeader: {251+ wwwAuthenticateHeader: () => ({252+ error: 'Unauthorized',253+ error_description: 'Unauthorized',254+ }),255+ },256+ })257+ )258+ app.get(259+ '/auth-custom-invalid-authentication-header-wwwAuthenticateHeader-function-object/*',260+ (c) => {261+ handlerExecuted = true262+ return c.text('auth')263+ }264+ )265+266+ app.use(267 '/auth-custom-invalid-authentication-header-message-string/*',268 bearerAuth({269 token,129- invalidAuthenticationHeaderMessage:130- 'Custom invalid authentication header message as string',270+ invalidAuthenticationHeader: {271+ message: 'Custom invalid authentication header message as string',272+ },273 })274 )275 app.get('/auth-custom-invalid-authentication-header-message-string/*', (c) => {276 handlerExecuted = true3 unmodified lines280 app.use(281 '/auth-custom-invalid-authentication-header-message-object/*',282 bearerAuth({283 token,142- invalidAuthenticationHeaderMessage: {143- message: 'Custom invalid authentication header message as object',284+ invalidAuthenticationHeader: {285+ message: {286+ message: 'Custom invalid authentication header message as object',287+ },288 },289 })290 )291 app.get('/auth-custom-invalid-authentication-header-message-object/*', (c) => {4 unmodified lines296 app.use(297 '/auth-custom-invalid-authentication-header-message-function-string/*',298 bearerAuth({299 token,156- invalidAuthenticationHeaderMessage: () =>157- 'Custom invalid authentication header message as function string',300+ invalidAuthenticationHeader: {301+ message: () => 'Custom invalid authentication header message as function string',302+ },303 })304 )305 app.get('/auth-custom-invalid-authentication-header-message-function-string/*', (c) => {306 handlerExecuted = true3 unmodified lines310 app.use(311 '/auth-custom-invalid-authentication-header-message-function-object/*',312 bearerAuth({313 token,169- invalidAuthenticationHeaderMessage: () => ({170- message: 'Custom invalid authentication header message as function object',171- }),314+ invalidAuthenticationHeader: {315+ message: () => ({316+ message: 'Custom invalid authentication header message as function object',317+ }),318+ },319 })320 )321 app.get('/auth-custom-invalid-authentication-header-message-function-object/*', (c) => {322 handlerExecuted = true323 return c.text('auth')324 })325 326 app.use(327+ '/auth-custom-invalid-token-wwwAuthenticateHeader-string/*',328+ bearerAuth({329+ token: tokens,330+ invalidToken: {331+ wwwAuthenticateHeader: 'Bearer error="Unauthorized",error_description="Unauthorized"',332+ },333+ })334+ )335+ app.get('/auth-custom-invalid-token-wwwAuthenticateHeader-string/*', (c) => {336+ handlerExecuted = true337+ return c.text('auth')338+ })339+340+ app.use(341+ '/auth-custom-invalid-token-wwwAuthenticateHeader-object/*',342+ bearerAuth({343+ token: tokens,344+ invalidToken: {345+ wwwAuthenticateHeader: {346+ error: 'Unauthorized',347+ error_description: 'Unauthorized',348+ },349+ },350+ })351+ )352+ app.get('/auth-custom-invalid-token-wwwAuthenticateHeader-object/*', (c) => {353+ handlerExecuted = true354+ return c.text('auth')355+ })356+357+ app.use(358+ '/auth-custom-invalid-token-wwwAuthenticateHeader-function-string/*',359+ bearerAuth({360+ token: tokens,361+ invalidToken: {362+ wwwAuthenticateHeader: () =>363+ 'Bearer error="Unauthorized",error_description="Unauthorized"',364+ },365+ })366+ )367+ app.get('/auth-custom-invalid-token-wwwAuthenticateHeader-function-string/*', (c) => {368+ handlerExecuted = true369+ return c.text('auth')370+ })371+372+ app.use(373+ '/auth-custom-invalid-token-wwwAuthenticateHeader-function-object/*',374+ bearerAuth({375+ token: tokens,376+ invalidToken: {377+ wwwAuthenticateHeader: () => ({378+ error: 'Unauthorized',379+ error_description: 'Unauthorized',380+ }),381+ },382+ })383+ )384+ app.get('/auth-custom-invalid-token-wwwAuthenticateHeader-function-object/*', (c) => {385+ handlerExecuted = true386+ return c.text('auth')387+ })388+389+ app.use(390 '/auth-custom-invalid-token-message-string/*',391 bearerAuth({392 token,183- invalidTokenMessage: 'Custom invalid token message as string',393+ invalidToken: { message: 'Custom invalid token message as string' },394 })395 )396 app.get('/auth-custom-invalid-token-message-string/*', (c) => {397 handlerExecuted = true3 unmodified lines401 app.use(402 '/auth-custom-invalid-token-message-object/*',403 bearerAuth({404 token,195- invalidTokenMessage: { message: 'Custom invalid token message as object' },405+ invalidToken: { message: { message: 'Custom invalid token message as object' } },406 })407 )408 app.get('/auth-custom-invalid-token-message-object/*', (c) => {409 handlerExecuted = true3 unmodified lines413 app.use(414 '/auth-custom-invalid-token-message-function-string/*',415 bearerAuth({416 token,207- invalidTokenMessage: () => 'Custom invalid token message as function string',417+ invalidToken: { message: () => 'Custom invalid token message as function string' },418 })419 )420 app.get('/auth-custom-invalid-token-message-function-string/*', (c) => {421 handlerExecuted = true3 unmodified lines425 app.use(426 '/auth-custom-invalid-token-message-function-object/*',427 bearerAuth({428 token,429+ invalidToken: {219- invalidTokenMessage: () => ({220- message: 'Custom invalid token message as function object',221- }),430+ message: () => ({431+ message: 'Custom invalid token message as function object',432+ }),433+ },434 })435 )436 app.get('/auth-custom-invalid-token-message-function-object/*', (c) => {437 handlerExecuted = true159 unmodified lines597 expect(res.status).toBe(401)598 expect(await res.text()).toBe('Unauthorized')599 })600 601+ it('Should not authorize - custom no authorization header wwwAuthenticateHeader as string', async () => {602+ const req = new Request(603+ 'http://localhost/auth-custom-no-authentication-header-wwwAuthenticateHeader-string'604+ )605+ const res = await app.request(req)606+ expect(res).not.toBeNull()607+ expect(res.status).toBe(401)608+ expect(handlerExecuted).toBeFalsy()609+ expect(res.headers.get('WWW-Authenticate')).toBe(610+ 'Bearer error="Unauthorized",error_description="Unauthorized"'611+ )612+ })613+614+ it('Should not authorize - custom no authorization header wwwAuthenticateHeader as object', async () => {615+ const req = new Request(616+ 'http://localhost/auth-custom-no-authentication-header-wwwAuthenticateHeader-object'617+ )618+ const res = await app.request(req)619+ expect(res).not.toBeNull()620+ expect(res.status).toBe(401)621+ expect(handlerExecuted).toBeFalsy()622+ expect(res.headers.get('WWW-Authenticate')).toBe(623+ 'Bearer error="Unauthorized",error_description="Unauthorized"'624+ )625+ })626+627+ it('Should not authorize - custom no authorization header wwwAuthenticateHeader as function string', async () => {628+ const req = new Request(629+ 'http://localhost/auth-custom-no-authentication-header-wwwAuthenticateHeader-function-string'630+ )631+ const res = await app.request(req)632+ expect(res).not.toBeNull()633+ expect(res.status).toBe(401)634+ expect(handlerExecuted).toBeFalsy()635+ expect(res.headers.get('WWW-Authenticate')).toBe(636+ 'Bearer error="Unauthorized",error_description="Unauthorized"'637+ )638+ })639+640+ it('Should not authorize - custom no authorization header wwwAuthenticateHeader as function object', async () => {641+ const req = new Request(642+ 'http://localhost/auth-custom-no-authentication-header-wwwAuthenticateHeader-function-object'643+ )644+ const res = await app.request(req)645+ expect(res).not.toBeNull()646+ expect(res.status).toBe(401)647+ expect(handlerExecuted).toBeFalsy()648+ expect(res.headers.get('WWW-Authenticate')).toBe(649+ 'Bearer error="Unauthorized",error_description="Unauthorized"'650+ )651+ })652+653 it('Should not authorize - custom no authorization header message as string', async () => {654 const req = new Request('http://localhost/auth-custom-no-authentication-header-message-string')655 const res = await app.request(req)656 expect(res).not.toBeNull()36 unmodified lines693 '{"message":"Custom no authentication header message as function object"}'694 )695 })696 697+ it('Should not authorize - custom invalid authentication header wwwAuthenticateHeader as string', async () => {698+ const req = new Request(699+ 'http://localhost/auth-custom-invalid-authentication-header-wwwAuthenticateHeader-string'700+ )701+ req.headers.set('Authorization', 'Beare abcdefg12345-._~+/=')702+ const res = await app.request(req)703+ expect(res).not.toBeNull()704+ expect(res.status).toBe(400)705+ expect(handlerExecuted).toBeFalsy()706+ expect(res.headers.get('WWW-Authenticate')).toBe(707+ 'Bearer error="Unauthorized",error_description="Unauthorized"'708+ )709+ })710+711+ it('Should not authorize - custom invalid authentication header wwwAuthenticateHeader as object', async () => {712+ const req = new Request(713+ 'http://localhost/auth-custom-invalid-authentication-header-wwwAuthenticateHeader-object'714+ )715+ req.headers.set('Authorization', 'Beare abcdefg12345-._~+/=')716+ const res = await app.request(req)717+ expect(res).not.toBeNull()718+ expect(res.status).toBe(400)719+ expect(handlerExecuted).toBeFalsy()720+ expect(res.headers.get('WWW-Authenticate')).toBe(721+ 'Bearer error="Unauthorized",error_description="Unauthorized"'722+ )723+ })724+725+ it('Should not authorize - custom invalid authentication header wwwAuthenticateHeader as function string', async () => {726+ const req = new Request(727+ 'http://localhost/auth-custom-invalid-authentication-header-wwwAuthenticateHeader-function-string'728+ )729+ req.headers.set('Authorization', 'Beare abcdefg12345-._~+/=')730+ const res = await app.request(req)731+ expect(res).not.toBeNull()732+ expect(res.status).toBe(400)733+ expect(handlerExecuted).toBeFalsy()734+ expect(res.headers.get('WWW-Authenticate')).toBe(735+ 'Bearer error="Unauthorized",error_description="Unauthorized"'736+ )737+ })738+739+ it('Should not authorize - custom invalid authentication header wwwAuthenticateHeader as function object', async () => {740+ const req = new Request(741+ 'http://localhost/auth-custom-invalid-authentication-header-wwwAuthenticateHeader-function-object'742+ )743+ req.headers.set('Authorization', 'Beare abcdefg12345-._~+/=')744+ const res = await app.request(req)745+ expect(res).not.toBeNull()746+ expect(res.status).toBe(400)747+ expect(handlerExecuted).toBeFalsy()748+ expect(res.headers.get('WWW-Authenticate')).toBe(749+ 'Bearer error="Unauthorized",error_description="Unauthorized"'750+ )751+ })752+753 it('Should not authorize - custom invalid authentication header message as string', async () => {754 const req = new Request(755 'http://localhost/auth-custom-invalid-authentication-header-message-string'756 )46 unmodified lines803 '{"message":"Custom invalid authentication header message as function object"}'804 )805 })806 807+ it('Should not authorize - custom invalid token wwwAuthenticateHeader as string', async () => {808+ const req = new Request(809+ 'http://localhost/auth-custom-invalid-token-wwwAuthenticateHeader-string'810+ )811+ req.headers.set('Authorization', 'Bearer invalid-token')812+ const res = await app.request(req)813+ expect(res).not.toBeNull()814+ expect(res.status).toBe(401)815+ expect(handlerExecuted).toBeFalsy()816+ expect(res.headers.get('WWW-Authenticate')).toBe(817+ 'Bearer error="Unauthorized",error_description="Unauthorized"'818+ )819+ })820+821+ it('Should not authorize - custom invalid token wwwAuthenticateHeader as object', async () => {822+ const req = new Request(823+ 'http://localhost/auth-custom-invalid-token-wwwAuthenticateHeader-object'824+ )825+ req.headers.set('Authorization', 'Bearer invalid-token')826+ const res = await app.request(req)827+ expect(res).not.toBeNull()828+ expect(res.status).toBe(401)829+ expect(handlerExecuted).toBeFalsy()830+ expect(res.headers.get('WWW-Authenticate')).toBe(831+ 'Bearer error="Unauthorized",error_description="Unauthorized"'832+ )833+ })834+835+ it('Should not authorize - custom invalid token wwwAuthenticateHeader as function string', async () => {836+ const req = new Request(837+ 'http://localhost/auth-custom-invalid-token-wwwAuthenticateHeader-function-string'838+ )839+ req.headers.set('Authorization', 'Bearer invalid-token')840+ const res = await app.request(req)841+ expect(res).not.toBeNull()842+ expect(res.status).toBe(401)843+ expect(handlerExecuted).toBeFalsy()844+ expect(res.headers.get('WWW-Authenticate')).toBe(845+ 'Bearer error="Unauthorized",error_description="Unauthorized"'846+ )847+ })848+849+ it('Should not authorize - custom invalid token wwwAuthenticateHeader as function object', async () => {850+ const req = new Request(851+ 'http://localhost/auth-custom-invalid-token-wwwAuthenticateHeader-function-object'852+ )853+ req.headers.set('Authorization', 'Bearer invalid-token')854+ const res = await app.request(req)855+ expect(res).not.toBeNull()856+ expect(res.status).toBe(401)857+ expect(handlerExecuted).toBeFalsy()858+ expect(res.headers.get('WWW-Authenticate')).toBe(859+ 'Bearer error="Unauthorized",error_description="Unauthorized"'860+ )861+ })862+863 it('Should not authorize - custom invalid token message as string', async () => {864 const req = new Request('http://localhost/auth-custom-invalid-token-message-string')865 req.headers.set('Authorization', 'Bearer invalid-token')866 const res = await app.request(req)38 unmodified linesmodified:src/middleware/bearer-auth/index.ts+59 added-11 removed
12 unmodified lines1314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768696 unmodified lines767778795253548081828384858687888928 unmodified lines118119120121911221231241251261271281291309513113213313413513613713813914015 unmodified lines15615715815916011912016116216316416516616716816917017117217312913017417517617717817918018112 unmodified lines1941951961971981511521992002012022032043 unmodified lines12 unmodified linesconst PREFIX = 'Bearer'const HEADER = 'Authorization'
type MessageFunction = (c: Context) => string | object | Promise<string | object>type CustomizedErrorResponseOptions = { wwwAuthenticateHeader?: string | object | MessageFunction message?: string | object | MessageFunction}
type BearerAuthOptions = | { token: string | string[] realm?: string prefix?: string headerName?: string hashFunction?: Function /** * @deprecated Use noAuthenticationHeader.message instead */ noAuthenticationHeaderMessage?: string | object | MessageFunction noAuthenticationHeader?: CustomizedErrorResponseOptions /** * @deprecated Use invalidAuthenticationHeader.message instead */ invalidAuthenticationHeaderMessage?: string | object | MessageFunction invalidAuthenticationHeader?: CustomizedErrorResponseOptions /** * @deprecated Use invalidToken.message instead */ invalidTokenMessage?: string | object | MessageFunction invalidToken?: CustomizedErrorResponseOptions } | { realm?: string prefix?: string headerName?: string verifyToken: (token: string, c: Context) => boolean | Promise<boolean> hashFunction?: Function /** * @deprecated Use noAuthenticationHeader.message instead */ noAuthenticationHeaderMessage?: string | object | MessageFunction noAuthenticationHeader?: CustomizedErrorResponseOptions /** * @deprecated Use invalidAuthenticationHeader.message instead */ invalidAuthenticationHeaderMessage?: string | object | MessageFunction invalidAuthenticationHeader?: CustomizedErrorResponseOptions /** * @deprecated Use invalidToken.message instead */ invalidTokenMessage?: string | object | MessageFunction invalidToken?: CustomizedErrorResponseOptions }
/** * Bearer Auth Middleware for Hono.6 unmodified lines * @param {string} [options.realm=""] - The domain name of the realm, as part of the returned WWW-Authenticate challenge header. * @param {string} [options.prefix="Bearer"] - The prefix (or known as `schema`) for the Authorization header value. If set to the empty string, no prefix is expected. * @param {string} [options.headerName=Authorization] - The header name. * @param {Function} [options.hashFunction] - A function to handle hashing for safe comparison of authentication tokens. * @param {string | object | MessageFunction} [options.noAuthenticationHeaderMessage="Unauthorized"] - The no authentication header message. * @param {string | object | MessageFunction} [options.invalidAuthenticationHeaderMessage="Bad Request"] - The invalid authentication header message. * @param {string | object | MessageFunction} [options.invalidTokenMessage="Unauthorized"] - The invalid token message. * @param {string | object | MessageFunction} [options.noAuthenticationHeader.message="Unauthorized"] - The no authentication header message. * @param {string | object | MessageFunction} [options.noAuthenticationHeader.wwwAuthenticateHeader="Bearer realm=\"\""] - The response header value for the WWW-Authenticate header when no authentication header is provided. * @param {string | object | MessageFunction} [options.invalidAuthenticationHeader.message="Bad Request"] - The invalid authentication header message. * @param {string | object | MessageFunction} [options.invalidAuthenticationHeader.wwwAuthenticateHeader="Bearer error=\"invalid_request\""] - The response header value for the WWW-Authenticate header when authentication header is invalid. * @param {string | object | MessageFunction} [options.invalidToken.message="Unauthorized"] - The invalid token message. * @param {string | object | MessageFunction} [options.invalidToken.wwwAuthenticateHeader="Bearer error=\"invalid_token\""] - The response header value for the WWW-Authenticate header when token is invalid. * @returns {MiddlewareHandler} The middleware handler function. * @throws {Error} If neither "token" nor "verifyToken" options are provided. * @throws {HTTPException} If authentication fails, with 401 status code for missing or invalid token, or 400 status code for invalid request. *28 unmodified lines
const throwHTTPException = async ( c: Context, status: ContentfulStatusCode, wwwAuthenticateHeader: string, wwwAuthenticateHeader: string | object | MessageFunction, messageOption: string | object | MessageFunction ): Promise<Response> => { const wwwAuthenticateHeaderValue: string | object = typeof wwwAuthenticateHeader === 'function' ? await wwwAuthenticateHeader(c) : wwwAuthenticateHeader
const headers = { 'WWW-Authenticate': wwwAuthenticateHeader, 'WWW-Authenticate': typeof wwwAuthenticateHeaderValue === 'string' ? wwwAuthenticateHeaderValue : `${wwwAuthenticatePrefix}${Object.entries(wwwAuthenticateHeaderValue) .map(([key, value]) => `${key}="${value}"`) .join(',')}`, } const responseMessage = typeof messageOption === 'function' ? await messageOption(c) : messageOption const res =15 unmodified lines // No Authorization header await throwHTTPException( c, 401, options.noAuthenticationHeader?.wwwAuthenticateHeader || `${wwwAuthenticatePrefix}realm="${realm}"`, options.noAuthenticationHeaderMessage || 'Unauthorized' `${wwwAuthenticatePrefix}realm="${realm}"`, options.noAuthenticationHeader?.message || options.noAuthenticationHeaderMessage || 'Unauthorized' ) } else { const match = regexp.exec(headerToken) if (!match) { // Invalid Request await throwHTTPException( c, 400, options.invalidAuthenticationHeader?.wwwAuthenticateHeader || `${wwwAuthenticatePrefix}error="invalid_request"`, options.invalidAuthenticationHeaderMessage || 'Bad Request' `${wwwAuthenticatePrefix}error="invalid_request"`, options.invalidAuthenticationHeader?.message || options.invalidAuthenticationHeaderMessage || 'Bad Request' ) } else { let equal = false if ('verifyToken' in options) {12 unmodified lines // Invalid Token await throwHTTPException( c, 401, options.invalidToken?.wwwAuthenticateHeader || `${wwwAuthenticatePrefix}error="invalid_token"`, options.invalidTokenMessage || 'Unauthorized' `${wwwAuthenticatePrefix}error="invalid_token"`, options.invalidToken?.message || options.invalidTokenMessage || 'Unauthorized' ) } } }3 unmodified lines