angel3_auth 10.0.2
angel3_auth: ^10.0.2 copied to clipboard
A complete authentication plugin for Angel3. Includes support for stateless JWT tokens, Basic Auth, and more.
Angel3 Authentication #
Authentication for Angel3, inspired by Passport. You register strategies, such as a username and password, and AngelAuth signs the user in with them. It issues a JWT, and gives every later request that carries the JWT its user. The User Guide has more details.
Installation #
In your pubspec.yaml:
dependencies:
angel3_auth: ^10.0.0
Strategies #
- Bundled.
LocalAuthStrategychecks a username and password, from the form or, withallowBasic, from anAuthorization: Basicheader. - Others. Strategies such as OAuth2 (
angel3_auth_client) and Twitter are separate packages on pub.
Usage #
Read the User Guide first. Then:
- Create an
AngelAuth. Itsserializerturns a user into an id for the JWT, and itsdeserializerturns that id back into a user. - Configure the app with it.
- Register strategies under names, and route
authenticatewith a name.
import 'package:angel3_auth/angel3_auth.dart';
import 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_framework/http.dart';
void main() async {
var app = Angel();
var auth = AngelAuth<User>(
serializer: (user) => user.id ?? '',
deserializer: (id) => fetchAUserByIdSomehow(id),
);
// Reads the JWT of each request, and gives its user to the handlers.
await app.configure(auth.configureServer);
auth.strategies['local'] = LocalAuthStrategy((username, password) {
// Look the user up. Return them if the password is right, or `null`.
return null;
});
app.post('/auth/local', auth.authenticate('local'));
var http = AngelHttp(app);
await http.startServer('127.0.0.1', 3000);
}
class User {
String? id, username, password;
}
Future<User> fetchAUserByIdSomehow(String id) async {
// Fetch a user somehow...
throw UnimplementedError();
}
configureServer also routes POST /auth/token, which exchanges a JWT for a new one (see Security defaults). Configuring the same app again with the same AngelAuth does nothing. Configuring it with another AngelAuth of the same user type throws.
Trying several strategies #
Give authenticate a list of names, or a single comma-separated string such as 'local,basic':
auth.strategies['basic'] =
LocalAuthStrategy(verifyPasswordSomehow, allowBasic: true);
app.post('/auth/any', auth.authenticate(['local', 'basic']));
- The strategies are tried in turn. When one succeeds, the rest are skipped.
- A strategy that fails returns
null, so the next one is tried. - A strategy that answers the request itself, such as with a redirect, stops the loop.
- If the last one fails, the answer is a
401 Not Authenticated, or a redirect tofailureRedirectif it is given. - A name that has no strategy throws an
ArgumentError.
LocalAuthStrategy returns null when the form has no valid credentials. Invalid Basic credentials, and forceBasic, answer a 401 with a Basic challenge.
What a login answers #
Once a strategy succeeds, authenticate issues a JWT and sets the token cookie. Then it answers in the first way that applies, from the AngelAuthOptions you pass it:
tokenCallback, given theAuthTokenand the user. If it returns something other thannull, that is the answer. Otherwise the login continues, with any changes the callback made to the token.callback, given the JWT, such asconfirmPopupAuthentication()(see Popup authentication).successRedirect: a redirect to it.- JSON:
{"data": user, "token": jwt}, if the request accepts JSON andcanRespondWithJsonistrue, which is the default. trueotherwise, so that the next handler runs, as for Basic authentication.
onLogin tells you of every new login once it is accepted, however it is answered. It is not told of a login that tokenCallback refuses, nor of a user who was already signed in.
To sign a user in from your own code, use login with an AuthToken you have verified, for example with AuthToken.validate, or loginById with a user id. Both throw a 403 if the user doesn't exist. If the request already has a user, it keeps that user, and the new one applies from the next request.
Protecting routes #
A handler gets the request's user with req.container!.makeAsync<User>().
requireAuthentication<User>()refuses a request without a user with a 403. Called withthrowError: false, it returnsfalseinstead.forceBasicAuth<User>()answers a request with no JWT with a 401 and aWWW-Authenticate: Basicchallenge, so a browser asks for a username and password. Its realm isangel3_authby default; passrealmfor another one.- An invalid JWT, such as one that has expired, gets a 403 from both.
app.get('/me', chain([
requireAuthentication<User>(),
(req, res) => req.container!.makeAsync<User>(),
]));
Logging out #
logout expires the token cookie, tells onLogout, and redirects to successRedirect if you give one. No handler after it runs once it has redirected.
app.post('/auth/logout', auth.logout(AngelAuthOptions(successRedirect: '/')));
A JWT is not revoked. A copy of it stays valid until it expires.
Security defaults #
- JWT lifetime. A JWT expires after a day. Set
jwtLifeSpan, in milliseconds, for another lifetime.-1means it never expires, and a warning is logged if you also give a fixedjwtKey. - The JWT key. Without a
jwtKey, a random one is made on each start, so JWTs don't survive a restart and differ between instances. Give a fixed key from a secret to share them. - Renewing.
POST /auth/tokenexchanges a JWT that is still valid for a new one. An expired JWT is renewed only withinreviveGracePeriod, which is none by default. The user must still exist. - The cookie. The
tokencookie isHttpOnly,SecureandSameSite=Lax; changeSameSitewithcookieSameSite. It is set when a user logs in or a JWT is renewed, not for requests that use anAuthorization: Bearerheader.logoutexpires it. - IP address. With
enforceIp, which is on by default, a JWT is refused when it is used from a different IP address than the one it was issued to. - The query string. A JWT in the query (
?token=) is ignored unlessallowTokenInQueryistrue, because query strings end up in logs, browser history andRefererheaders. - Claims. JWTs have
"iss": "angel3_auth", and the standardiatandexpclaims in seconds.
Popup authentication #
Single-page apps often open an OAuth login in a separate window. angel3_client supports this, and works with the confirmPopupAuthentication callback of this package:
Future<void> configureServer(Angel app) async {
app.get(
'/auth/facebook',
auth.authenticate(
'facebook',
AngelAuthOptions(callback: confirmPopupAuthentication()),
),
);
}
It renders a small HTML page that sends the user's JWT to window.opener as a token event, and closes the window. Pass eventName for another event name. angel3_client exposes the event as a Stream:
app.authenticateViaPopup('/auth/google').listen((jwt) {
// Do something with the JWT
});
Migrating from 9.x to 10.0.0 #
The CHANGELOG lists the breaking changes of each release. These are the ones in 10.0.0 that may need changes in an app:
-
JWT lifetime. A JWT expires after a day by default (
AngelAuth.defaultJwtLifeSpan). PassjwtLifeSpan, in milliseconds, for another lifetime.-1never expires, and a warning is logged if you also give a fixedjwtKey. -
Renewing JWTs.
POST /auth/tokenrenews a JWT that is still valid. It renews an expired one only withinreviveGracePeriod, which is none by default, and only if its user still exists. Clients that renewed expired JWTs must log in again, unless you give a grace period:var auth = AngelAuth<User>( serializer: (user) => user.id ?? '', deserializer: (id) => fetchAUserByIdSomehow(id), reviveGracePeriod: const Duration(days: 7), ); -
Cookie. The
tokencookie isSameSite=Lax(cookieSameSite). It is set only when a user logs in or a JWT is renewed, not for requests with anAuthorization: Bearerheader. -
Token in the query string.
?token=is ignored unlessallowTokenInQueryistrue. Enable it for the browser WebSocket client ofangel3_websocket, which cannot send headers. -
Claims. JWTs have the standard
iatandexpclaims, in seconds. JWTs issued by 9.x are still read.