dox_auth 3.0.0-rc.1
dox_auth: ^3.0.0-rc.1 copied to clipboard
Authentication package for dox framework with JWT and session drivers.
dox_auth #
Login for Dox apps. It checks an email and a password. It gives back a JWT token for an API, or keeps the login in the session for web pages.
Part of Dox, a web backend framework for Dart, like Laravel. Source code: github.com/dartondox/dox.
Install #
dart pub add dox_auth
Dox 3.x is in alpha (3.0.0-alpha.x). The API can still change before the stable release.
A new app made with dox create already has it.
Use it #
Set it up in a provider:
import 'package:dox_auth/dox_auth.dart';
import 'package:dox_core/dox_core.dart';
class AppAuthProvider extends DoxProvider {
@override
void setup() {
Auth.initialize(AuthConfig(
defaultGuard: 'web',
guards: <String, AuthGuard>{
'web': AuthGuard(
driver: JwtAuthDriver(
secret: SecretKey(Env.get('APP_KEY')),
expiresIn: const Duration(days: 7),
),
provider: AuthProvider(model: () => User()),
),
},
));
}
}
Log in, and protect a route:
String? token = await Auth().attempt(<String, dynamic>{
'email': 'ada@example.com',
'password': 'secret',
}); // null when the email or password is wrong
Route.get('/auth/user', <dynamic>[AuthMiddleware(), authController.user]);
After AuthMiddleware, req.auth?.user<User>() is the logged in user.
For web pages, use SessionAuthDriver() in the guard. It needs SessionMiddleware:
bool ok = await Auth().attemptSession(req, credentials); // false when wrong
Auth().logout(req);
Route.get('/dashboard', <dynamic>[AuthMiddleware(redirectTo: '/login'), pageController.dashboard]);
Features #
- JWT driver (
JwtAuthDriver) with a secret, algorithm, expiry and issuer. - Session driver (
SessionAuthDriver) for web pages. Login and logout give the session a new id. Auth().attempt(credentials)finds the user and checks the bcrypt hash.Auth().login(user)gives a token with no password check.- Custom drivers, like an API key guard.
Auth().setUser(req, user)sets the user from your own middleware. AuthMiddlewareanswers401when the user is not logged in. WithredirectTo, it sends the user to that page instead.- More than one guard, like
webandadmin, each with its own driver and user model. - The user is loaded from the database on each request with
dox_orm.
Things to know: a token expires after 1 hour by default. Change it with expiresIn.
There is no server list of tokens, so you can not cancel one token.
A session login ends with Auth().logout(req).
With the default cookie session driver, all session data sits in the cookie. So an old copy of the cookie still works after logout. If logout must really end old cookies, use the cache session driver, like SessionConfig(driver: 'cache', store: 'redis').
Custom guard (API key) #
You can check the user in your own way, like an API key in the header.
Write a driver: extend AuthDriver and return the user from verifyToken.
AuthMiddleware and req.auth then work as with the other drivers.
/// `Authorization: Bearer <api key>` gives the user with this key.
class ApiKeyAuthDriver extends AuthDriver {
@override
Future<Model<dynamic>?> verifyToken(IDoxRequest req, String guard) async {
String header = req.header('Authorization') ?? '';
if (!header.startsWith('Bearer ')) return null;
Model<dynamic> model = AuthEngine().guard(guard).provider.model();
return await model.where('api_key', header.substring(7).trim()).getFirst();
}
/// no password login for this guard
@override
Future<Model<dynamic>?> attempt(Map<String, dynamic> credentials, String guard) async => null;
/// no token to make: the key is the token
@override
String? createToken(Map<String, dynamic>? userPayload, String guard) => null;
}
Add it as a guard, and use the guard in the route:
'api': AuthGuard(
driver: ApiKeyAuthDriver(),
provider: AuthProvider(model: () => User()),
),
Route.get('/api/me', <dynamic>[AuthMiddleware(guard: 'api'), (DoxRequest req) => req.auth?.user<User>()]);
Store a hash of the key, not the key itself, and compare the hash.
If you already have your own middleware, set the user with Auth().setUser(req, user).
It needs no token and no password check. req.auth then gives this user:
User? user = await keys.userForKey(key);
if (user == null) throw UnAuthorizedException();
Auth(guard: 'api').setUser(req, user);
return req;
Documentation #
License #
MIT. See LICENSE.