added basic auth
This commit is contained in:
46
middleware.js
Normal file
46
middleware.js
Normal file
@ -0,0 +1,46 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
export function middleware(req) {
|
||||
const basicAuth = req.headers.get('authorization');
|
||||
const url = req.nextUrl;
|
||||
|
||||
// Read credentials from environment variables
|
||||
const user = process.env.BASIC_AUTH_USER;
|
||||
const pwd = process.env.BASIC_AUTH_PASSWORD;
|
||||
|
||||
if (user && pwd) {
|
||||
if (basicAuth) {
|
||||
const authValue = basicAuth.split(' ')[1];
|
||||
const [providedUser, providedPwd] = atob(authValue).split(':');
|
||||
|
||||
if (providedUser === user && providedPwd === pwd) {
|
||||
return NextResponse.next();
|
||||
}
|
||||
}
|
||||
|
||||
// Return 401 Unauthorized if credentials don't match or are missing
|
||||
return new NextResponse('Auth required', {
|
||||
status: 401,
|
||||
headers: {
|
||||
'WWW-Authenticate': 'Basic realm="Secure Area"',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// If no credentials are set in ENV, just allow access
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
// Ensure the middleware only runs for paths that need protection.
|
||||
// Exclude static assets, API routes if public (though we probably want API secure too), and Next.js internals.
|
||||
export const config = {
|
||||
matcher: [
|
||||
/*
|
||||
* Match all request paths except for the ones starting with:
|
||||
* - _next/static (static files)
|
||||
* - _next/image (image optimization files)
|
||||
* - favicon.ico (favicon file)
|
||||
*/
|
||||
'/((?!_next/static|_next/image|favicon.ico).*)',
|
||||
],
|
||||
};
|
||||
Reference in New Issue
Block a user