basic_auth_middleware.dart 896 B

123456789101112131415161718192021222324252627282930
  1. import 'package:shelf/shelf.dart';
  2. Middleware basicAuthMiddleware({
  3. required String username,
  4. required String password,
  5. String realm = 'Secured Area',
  6. }) {
  7. // final validAuth = 'Basic ' + base64Encode(utf8.encode('$username:$password'));
  8. return (Handler innerHandler) {
  9. return (Request request) async {
  10. // If no auth header is present or if it's invalid
  11. if (!request.headers
  12. .containsKey('authorization') /*|| authHeader != validAuth*/) {
  13. // Return 401 with WWW-Authenticate header to trigger browser prompt
  14. return Response(
  15. 401,
  16. body: 'Authorization Required',
  17. headers: {
  18. 'WWW-Authenticate': 'Basic realm="$realm"',
  19. 'Content-Type': 'text/plain',
  20. },
  21. );
  22. }
  23. // If auth is valid, proceed with the request
  24. return await innerHandler(request);
  25. };
  26. };
  27. }