1- import { NextApiRequest , NextApiResponse } from 'next'
21import type { NextRequest } from 'next/server'
32import { NextResponse } from 'next/server'
43import { basicAuthentication } from './lib/auth'
@@ -16,12 +15,22 @@ import { MiddlewareOptions } from './types'
1615 * @returns Either a 401 error or goes to the next page
1716 */
1817export const createNextAuthMiddleware =
19- ( { pathname = '/api/auth' , users = [ ] } : MiddlewareOptions = { } ) =>
18+ ( {
19+ pathname = '/api/auth' ,
20+ users = [ ] ,
21+ message = 'Authentication failed' ,
22+ realm = 'protected' ,
23+ } : MiddlewareOptions = { } ) =>
2024 ( req : NextRequest ) =>
21- nextBasicAuthMiddleware ( { pathname, users } , req )
25+ nextBasicAuthMiddleware ( { pathname, users, message , realm } , req )
2226
2327export const nextBasicAuthMiddleware = (
24- { pathname = '/api/auth' , users = [ ] } : MiddlewareOptions = { } ,
28+ {
29+ pathname = '/api/auth' ,
30+ users = [ ] ,
31+ message = 'Authentication failed' ,
32+ realm = 'protected' ,
33+ } : MiddlewareOptions = { } ,
2534 req : NextRequest
2635) => {
2736 // Check if credentials are set up
@@ -49,19 +58,8 @@ export const nextBasicAuthMiddleware = (
4958
5059 url . pathname = pathname
5160
52- return NextResponse . rewrite ( url )
61+ return new NextResponse ( message , {
62+ status : 401 ,
63+ headers : { 'WWW-Authenticate' : `Basic realm="${ realm } "` } ,
64+ } )
5365}
54-
55- /**
56- * Create an API page that handles returning a 401 authentication failed message
57- * @param realm The protection space
58- * @param message Message you want to show to the users
59- * @returns Next API page
60- */
61- export const createApiPage =
62- ( realm = 'protected' , message = 'Authentication failed' ) =>
63- ( _ : NextApiRequest , res : NextApiResponse ) => {
64- res . setHeader ( 'WWW-Authenticate' , `Basic realm="${ realm } "` )
65- res . statusCode = 401
66- res . end ( message )
67- }
0 commit comments