| 12345678910111213141516171819202122232425262728293031 |
- import 'package:shelf/shelf.dart';
- Middleware basicAuthMiddleware({
- required String username,
- required String password,
- String realm = 'Secured Area',
- }) {
- // final validAuth = 'Basic ' + base64Encode(utf8.encode('$username:$password'));
- return (Handler innerHandler) {
- return (Request request) async {
- final authHeader = request.headers['authorization'];
- // If no auth header is present or if it's invalid
- if (authHeader == null /*|| authHeader != validAuth*/) {
- // Return 401 with WWW-Authenticate header to trigger browser prompt
- return Response(
- 401,
- body: 'Authorization Required',
- headers: {
- 'WWW-Authenticate': 'Basic realm="$realm"',
- 'Content-Type': 'text/plain',
- },
- );
- }
- // If auth is valid, proceed with the request
- return await innerHandler(request);
- };
- };
- }
|