Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions docs/docs/advanced/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,36 @@ Handler middleware(Handler handler) {

In the above example, only routes that are not `POST` will have authentication checked.

### Custom Authenticated Responses

In some applications, you'll wish to send a custom response when the request is unauthenticated.
For example, a website will probably send an HTML page explaining to the user they need to log in before accessing the site.

To accomplish this, simply pass a `Handler` to the `unauthenticatedResponse` parameter to your authentication middleware.

```dart
Handler middleware(Handler handler) {
final userRepository = UserRepository();

return handler
.use(requestLogger())
.use(provider<UserRepository>((_) => userRepository))
.use(
basicAuthentication<User>(
authenticator: (context, username, password) {
final userRepository = context.read<UserRepository>();
return userRepository.userFromCredentials(username, password);
},
unauthenticatedResponse : (RequestContext context) async =>
Response(
body: '<html><body>You are not logged in :(</body></html>',
statusCode: HttpStatus.unauthorized,
),
),
);
}
```

### Authentication vs. Authorization

Both Authentication and authorization are related, but are different concepts that are often confused.
Expand Down
12 changes: 9 additions & 3 deletions packages/dart_frog_auth/lib/src/dart_frog_auth.dart
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ Middleware basicAuthentication<T extends Object>({
String password,
)? authenticator,
Applies applies = _defaultApplies,
Handler? unauthenticatedResponse,
Copy link
Contributor

@alestiago alestiago Jan 2, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am yet not sure if there could be a better API that the one suggested in the PR.

I think the main issue is that the existence of unauthenticatedResponse makes the programmer feel there should exist an authenticatedResponse counterpart. Then, having both exist makes me question if we could merge them into a single parameter and allow the user to dictate the logic.

I've been thinking about how would it look like if instead we had an responseOverride parameter where the programmer gets a user and decide how to handle the authorization; but it didn't convince me. Mainly because if you would only like to override the unauthenticated behavior the programmer would be forced to define the current default handler(context.provide(() => user)); for authenticated cases redundantly. In addition I feel that something similar could be achieved by chaining a middleware.

I have this other idea, where I think we should make a clear distinction between authentication and authorization. As of right now, the bearerAuthentication is doing both, authentication and authorization (despite its name being solely bearerAuthentication). The authorization logic is quite basic, if the authentication is a null user then deny access by returning an HttpStatus.unauthorized response. What we could do is introduce an authorizer parameter (that defaults to the current behavior user != null and returns an HttpStatus.unauthorized response). Yet, I'm not sure if we could provide a better API by leveraging the existing Dart Frog structure, for example by defining an Authorizer middleware.


Regarding the suggest API in this PR , a change I'm sure about is that if we end up going forward with it is renaming the parameter to remove the "Response" suffix, since it it not of type Response but Handler, here are some name alternatives:

  • onUnauthenticated
  • unauthenticatedHandler
  • onAuthenticationFailure

I tend to prefer onUnauthenticated.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should make a clear distinction between authentication and authorization

This makes a ton of sense to me and is possibly the root of why I felt this change was needed. But this could also be solved with #1652 (or something similar) by moving the authorization logic to the handler itself. For example

Response onRequest(RequestContext context) {
  final user = context.tryRead<User>();
  if (user == null) {
    // Unauthenticated
    return UnauthenticatedResponse();
  }
  if (!hasPermission(user)) {
    // Unauthorized
    return UnauthorizedResponse();
  }

  return RealResponse();
}

Overall I think this is a very transparent solution and is the most flexible. But currently this won't work because if you are unauthenticated, the middleware will just return a 401 response and your handler will never actually happen.

That would be a pretty big breaking change for the auth handlers, so maybe it could be opt-in with a parameter?

bearerAuthentication<User>(
  guarded: false // when true, a default 401 response will be returned. Otherwise, no user will be provided.
)

Or maybe it could be a separate middleware for that behavior?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we closed #1652 do we feel this is still needed? I'm still playing catch up 😅

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@felangel I still think there's a valid discussion here - basically right now, you can't use dart_frog_auth if you want routes that are optionally authenticated. Your only option if you want routes that might be authenticated is your own custom middleware.

That's fine, but imo it's a common enough task that it should be supported in the auth package.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

basically right now, you can't use dart_frog_auth if you want routes that are optionally authenticated.

@mtwichel I don't believe this is true! You can which routes are authenticated and which ones are not: https://dart-frog.dev/advanced/authentication/#filtering-routes

Or does this not work for you for some reason?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@erickzanardo The use case I'm describing is a little different than the filtering available. If you filter a route as unauthenticated, it doesn't provide any object to the handler. So, an attempt to context.read (for example) will fail with a state error.

What I'm looking for is support for routes that are optionally authenticated, whereas the current system only allows routes that are authenticated, or not.

For example, a web page that returns a slightly different UI if the user is authenticated (say, their picture in the top right), than if they are unauthenticated (maybe there'd be a login button instead of the picture). Currently to do this, you have to make your own authentication middleware and it's not supported by the dart_frog_auth.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another solution to this problem is something like #1651. The issue is that if you attempt to context.read something that hasn't been provided, it throws an error. Sure, you could write

final User? user;
try {
  user = context.read<User>();
} on StateError catch (_) {
  user = null;
}

But I think it's a bit clunky to do this every time. In practice you could (and I have) just wrapped this logic in an extension method, but it seems a common enough use case that imo dart_frog_auth should support routes that can be access by unauthenticated and authenticated routes alike.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mtwichel wouldn't the following work:

final user = context.read<User?>();

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@felangel it won't work because the middleware will not call the route and will just return 401.

@mtwichel I think that for your case maybe something like this would work:

abstract class User {}
class AppUser extends User {}
class AnonymousUser extends User {}

Then on the middleware authenticator method you would return the AnonymousUser user when they are not authenticated yet? That way your route will be called and you can perform the proper checking to execute your logic.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ahh @erickzanardo that's an interesting approach I hadn't considered. So in the handler you'd write something like

final user = context.read<User>();

if (user is AnonymousUser) {
  return UnathenticatedResponse();
}

if (user is AppUser) {
  return AuthenticatedResponse(user.userId);
}

Honestly, that is way cleaner. I think we can close this, but I might open a new PR to add this use case to the docs if that's okay with yall

}) {
assert(
userFromCredentials != null || authenticator != null,
Expand Down Expand Up @@ -102,7 +103,8 @@ Middleware basicAuthentication<T extends Object>({
}
}

return Response(statusCode: HttpStatus.unauthorized);
return unauthenticatedResponse?.call(context) ??
Response(statusCode: HttpStatus.unauthorized);
};
}

Expand Down Expand Up @@ -134,6 +136,7 @@ Middleware bearerAuthentication<T extends Object>({
Future<T?> Function(String token)? userFromToken,
Future<T?> Function(RequestContext context, String token)? authenticator,
Applies applies = _defaultApplies,
Handler? unauthenticatedResponse,
}) {
assert(
userFromToken != null || authenticator != null,
Expand Down Expand Up @@ -162,7 +165,8 @@ Middleware bearerAuthentication<T extends Object>({
}
}

return Response(statusCode: HttpStatus.unauthorized);
return unauthenticatedResponse?.call(context) ??
Response(statusCode: HttpStatus.unauthorized);
};
}

Expand Down Expand Up @@ -195,6 +199,7 @@ Middleware cookieAuthentication<T extends Object>({
Map<String, String> cookies,
) authenticator,
Applies applies = _defaultApplies,
Handler? unauthenticatedResponse,
Copy link

@marcossevilla marcossevilla Aug 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as @alestiago said here, I prefer renaming to onUnauthorized:

Suggested change
Handler? unauthenticatedResponse,
Handler? onUnauthorized,

since we're returning an unauthorized status by default, but I'm also good with onUnauthenticated

}) {
return (handler) => (context) async {
if (!await applies(context)) {
Expand All @@ -210,6 +215,7 @@ Middleware cookieAuthentication<T extends Object>({
}
}

return Response(statusCode: HttpStatus.unauthorized);
return unauthenticatedResponse?.call(context) ??
Response(statusCode: HttpStatus.unauthorized);
};
}
252 changes: 252 additions & 0 deletions packages/dart_frog_auth/test/src/dart_frog_auth_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ class _MockRequestContext extends Mock implements RequestContext {}

class _MockRequest extends Mock implements Request {}

class _MockResponse extends Mock implements Response {}

class _User {
const _User(this.id);
final String id;
Expand Down Expand Up @@ -87,6 +89,60 @@ void main() {
},
);

group('and custom unauthenticated response is provided', () {
test(
'returns custom response when Authorization header is not present',
() async {
final response = _MockResponse();
final middleware = basicAuthentication<_User>(
userFromCredentials: (_, __) async => user,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);

test(
'returns custom response when Authorization header is present but '
'invalid',
() async {
final response = _MockResponse();
when(() => request.headers)
.thenReturn({'Authorization': 'not valid'});
final middleware = basicAuthentication<_User>(
userFromCredentials: (_, __) async => user,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);

test(
'returns custom response when Authorization header is present and '
'valid but no user is returned',
() async {
final response = _MockResponse();
when(() => request.headers).thenReturn({
'Authorization': 'Bearer 1234',
});
final middleware = basicAuthentication<_User>(
userFromCredentials: (_, __) async => null,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);
});

test(
'sets the user when everything is valid',
() async {
Expand Down Expand Up @@ -190,6 +246,60 @@ void main() {
},
);

group('and custom unauthenticated response is provided', () {
test(
'returns custom response when Authorization header is not present',
() async {
final response = _MockResponse();
final middleware = basicAuthentication<_User>(
authenticator: (_, __, ___) async => user,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);

test(
'returns custom response when Authorization header is present but '
'invalid',
() async {
final response = _MockResponse();
when(() => request.headers)
.thenReturn({'Authorization': 'not valid'});
final middleware = basicAuthentication<_User>(
authenticator: (_, __, ___) async => user,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);

test(
'returns custom response when Authorization header is present and '
'valid but no user is returned',
() async {
final response = _MockResponse();
when(() => request.headers).thenReturn({
'Authorization': 'Basic dXNlcjpwYXNz',
});
final middleware = basicAuthentication<_User>(
authenticator: (_, __, ___) async => null,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);
});

test(
'sets the user when everything is valid',
() async {
Expand Down Expand Up @@ -307,6 +417,60 @@ void main() {
},
);

group('and custom unauthenticated response is provided', () {
test(
'returns custom response when Authorization header is not present',
() async {
final response = _MockResponse();
final middleware = bearerAuthentication<_User>(
userFromToken: (_) async => user,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);

test(
'returns custom response when Authorization header is present but '
'invalid',
() async {
final response = _MockResponse();
when(() => request.headers)
.thenReturn({'Authorization': 'not valid'});
final middleware = bearerAuthentication<_User>(
userFromToken: (_) async => user,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);

test(
'returns custom response when Authorization header is present and '
'valid but no user is returned',
() async {
final response = _MockResponse();
when(() => request.headers).thenReturn({
'Authorization': 'Bearer 1234',
});
final middleware = bearerAuthentication<_User>(
userFromToken: (_) async => null,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);
});

test(
'sets the user when everything is valid',
() async {
Expand Down Expand Up @@ -410,6 +574,60 @@ void main() {
},
);

group('and custom unauthenticated response is provided', () {
test(
'returns custom response when Authorization header is not present',
() async {
final response = _MockResponse();
final middleware = bearerAuthentication<_User>(
authenticator: (_, __) async => user,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);

test(
'returns custom response when Authorization header is present but '
'invalid',
() async {
final response = _MockResponse();
when(() => request.headers)
.thenReturn({'Authorization': 'not valid'});
final middleware = bearerAuthentication<_User>(
authenticator: (_, __) async => user,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);

test(
'returns custom response when Authorization header is present and '
'valid but no user is returned',
() async {
final response = _MockResponse();
when(() => request.headers).thenReturn({
'Authorization': 'Bearer 1234',
});
final middleware = bearerAuthentication<_User>(
authenticator: (_, __) async => null,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);
});

test(
'sets the user when everything is valid',
() async {
Expand Down Expand Up @@ -504,6 +722,40 @@ void main() {
},
);

group('and custom unauthenticated response is provided', () {
test(
'returns custom response when Cookie header is not present',
() async {
final response = _MockResponse();
final middleware = cookieAuthentication<_User>(
authenticator: (_, __) async => user,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);

test(
'returns custom response when Cookie header is present '
'but no user is returned',
() async {
final response = _MockResponse();
when(() => request.headers).thenReturn({'Cookie': 'session=abc123'});
final middleware = cookieAuthentication<_User>(
authenticator: (_, __) async => null,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);
});

test(
'sets the user when everything is valid',
() async {
Expand Down
Loading