dox_auth 3.0.2
dox_auth: ^3.0.2 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-auth.
Install #
dart pub add dox_auth
To see what is ready and what may still change, read Status and roadmap.
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.
Change APP_KEY #
New tokens are signed with the current APP_KEY. To keep old tokens working after a key change, put the old key in AppConfig.previousKeys. The JWT driver checks a token with the current key first, then with each old key. An expired token still fails. Remove the old key once the old tokens have expired.
If the JWT secret is not APP_KEY, pass the old secrets to the driver: JwtAuthDriver(secret: SecretKey(newSecret), previousSecrets: <JWTKey>[SecretKey(oldSecret)]).
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. - Gates and policies for authorization, with the
Canmiddleware andreq.can.
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;
Authorization (gates and policies) #
Auth says who the user is. Gates and policies say what the user may do.
A gate is one rule. The types come from the function:
Gate.define('update-post', (User user, Post post) => post.userId == user.id);
Gate.define('create-post', (User user, _) => user.verified == true); // no subject
await Gate.allows(user, 'update-post', post); // true or false
await Gate.authorize(user, 'update-post', post); // 403 when denied
A policy holds the rules of one model:
class PostPolicy extends Policy<User, Post> {
bool create(User user) => user.verified == true;
bool update(User user, Post post) => post.userId == user.id;
@override
Map<String, Function> get abilities => <String, Function>{
'create': create,
'update': update,
};
}
Gate.policy<Post>(PostPolicy());
await Gate.allows(user, 'update', post);
await Gate.allows(user, 'create', Post); // no model: pass the type
In a controller, req.can, req.cannot and req.authorize use the user of req.auth.
On a route, use the Can middleware after AuthMiddleware.
A guest gets 401. A user who may not do it gets 403.
await req.authorize('update', post);
Route.post('/posts', <dynamic>[AuthMiddleware(), Can('create', subject: Post), postController.store]);
Route.put('/posts/{post}', <dynamic>[AuthMiddleware(), Can('update', param: 'post'), postController.update]);
With param, the subject is the value of Route.bind for that route param.
More:
- A check gives a
boolor aGateResponse.GateResponse.deny('Why')sets the message of the 403. Gate.before((User user, String ability) => user.isAdmin ? true : null)decides before every check.Gate.aftersees every answer, eg. to log it.Gate.anyandGate.allcheck a list of abilities.- A guest is denied, unless the user type is nullable, like
(User? user, Post post). - Gates and policies are kept per isolate. Dox runs many isolates, so register them in a
DoxProvidersetup(). It runs in every isolate.
Documentation #
License #
MIT. See LICENSE.