dox_auth 3.2.0
dox_auth: ^3.2.0 copied to clipboard
Authentication package for dox framework with session, JWT and access token drivers.
3.2.0 #
- New:
dox auth:install, run bydox add auth. It writeslib/config/auth.dart(anapiguard with access tokens),lib/providers/auth_provider.dartand the access tokens migration. It needs the ORM and theUsermodel: without them it stops with exit code 1 and changes nothing. It never overwrites a file. - Ships an AI agent skill (dox-auth-guide). Install it in your app with
dart run skills@ get. - New, opt-in:
AuthConfig(flags: AuthFlags(...)). Each flag turns on one Laravel behavior. All are off by default, so nothing changes.AuthFlags.all()turns on every flag.forbidGuest:req.authorize()andCangive a guest 403, not 401.jsonNoRedirect:AuthMiddleware(redirectTo: ...)gives a JSON or XHR client a 401, not a redirect. An Inertia request still gets the redirect.endSessionsOnPasswordChange: a session login ends when the user's password changes, like the LaravelAuthenticateSessionmiddleware. A session made before this release, or while the flag was off, has no stored value. It is not logged out; its first check stores the value. A user with no password gets a fixed value, so setting a first password also ends the old sessions. Note: a password change (orlogoutOtherDevices) before such a session's first request with the flag on does not end it, so a session stolen before the flag was on can stay. LaravelAuthenticateSessionworks the same. To end every old session once when you turn the flag on, changeAPP_KEYand do not add the old key topreviousKeys(this also ends other data made with the old key, like encrypted values and JWTs). With thecachesession driver, clearing the session store works too. The password column must give the same value on every read: a hook or cast that makes a new value each time ends every session. Pass a fully loaded user tologinSessionandupdateSessionPasswordHash: a model from aselect()with no password column ends the session on the next request. A rehash on login (Auth.needsRehash) changes the hash too, so it ends the user's other sessions, and the current one unless the app callsupdateSessionPasswordHashaftersave().
- New
Auth().logoutOtherDevices(req, password), like LaravelAuth::logoutOtherDevices. It checks the password, hashes it again and saves the user. All other sessions of the user end, and this one stays logged in. A wrong password throws anUnAuthorizedException. It ends the other sessions that were made or used while the flag was on. When a model hook stopssave(), it throws aStateErrorand the session does not change. Whensave()throws, the old hash is put back on the model and the error is thrown again. Limit the route, eg. with aLoginThrottle. It needs a session guard and theendSessionsOnPasswordChangeflag; without the flag it throws aStateErrorand changes nothing. - New
Auth().updateSessionPasswordHash(req, user): keeps the current session logged in after the app changes the password itself. With the flag off, it does nothing.usermust be the user of the session; another user throws anArgumentError. - With the flag on, a session login also keeps an HMAC-SHA256 of the user's password hash, with a key made from
APP_KEY(session keyauth_<guard>_password_hash). It is compared in constant time. A value made with one ofpreviousKeysstill matches, so anAPP_KEYchange does not log users out. With the flag off, nothing new is written to the session or read from it. - Docs: the
rotatedocs now say that an old token works on every route in its grace time, also on routes that make tokens. Only a second rotate is refused. Keepgraceshort. - Docs: the
needsRehashsample usesawait Hash.makeAsync(...). - New
Auth().rotateAccessToken(token, grace:, name:, expiresIn:): a new access token in place of an old one. It gets the user, name and abilities of the old token's row. The old token works forgracemore (default: it ends now). A token can be rotated only once: a second rotate throws anUnAuthorizedExceptionand makes nothing. A revoked or expired token is refused the same way. It runs in one transaction. A token of another guard, or a negativegrace, throws anArgumentError. The driver method isrotate(token, guard). rotateAccessTokenneeds a new nullablerotated_atcolumn in the token table.AccessTokenTables.up(and sodox auth:tokens-table) adds it to new tables. Existing apps that want to rotate tokens add it in a new migration:await schema.table('auth_access_tokens', (Table t) { t.dateTimeTz('rotated_at').nullable(); });. Without the column everything else works as before, and onlyrotateAccessTokenthrows aStateErrorthat says what to add.- New
Auth().setAccessTokenAbilities(token, abilities): changes the abilities of a token, eg. to add2faafter a two-step code. A revoked token throws anUnAuthorizedException, and a token of another guard anArgumentError. The driver method issetAbilities(token, guard, abilities). - New, opt-in:
AccessTokenAuthDriver(throwOnError: true). An error in a token check (a database error, a token row that can not be read, or a wrong guard setup) is thrown, not turned into a 401. It goes to the app'sExceptionHandler, so the app can answer 503, and a short database problem does not log the client out. The default does not change. AccessToken.abilitiesandAccessToken.expiresAtare notfinalany more: the two new methods update them.- Fix: after
once()orattempt()logged in another user,revokeToken()could still revoke the old access token of the request.once()andattempt()now drop that token too.login(),setUser()anduserFromToken()do the same when the user changes. - Fix:
once()andattempt()kept the access token of the request. After a login of another user,tokenCan()andcurrentAccessTokenstill used the old token. They now drop it. - Tests:
AuthMiddlewarewith several guards checks which guard let the user in, and a bad bearer token with a good session.once()counts in the login throttle and leaves the session empty.
3.1.0 #
No breaking change. Apps on 3.0.2 work the same with no code change, and no user is logged out. The new, safer features are opt-in.
- New
AuthMiddleware(guards: ['web', 'api']): tries several guards in order, like Laravelauth:web,api. The first good login setsreq.auth.AuthMiddleware(guard: ...)works as before. Setting both, or an empty list, throws anArgumentError. - New
Auth().check(): the same asisLoggedIn(), with the Laravel name. - New
Auth().once(credentials): checks the credentials and gives true or false, like LaravelAuth::once. The user is logged in for thisAuthonly: no token, no session. The throttle counts it likeattempt.attempt()still gives a token. - The error of
Auth().logout(req)on a JWT or access token guard now says to userevokeToken().logoutstill throws there: a silent no-op would leave the token working. - New
Auth().id(): the primary key of the logged-in user, or null for a guest. It works when the key is hidden fromtoJson(). NewAuth().guest(): true when nobody is logged in. - New
AuthMiddleware(optional: true): a good login setsreq.auth, and guests go through too, soreq.can()works on a public page. A bad, expired or revoked token is a guest. With the JWT and access token drivers, a database error is a guest too, but it is reported. With the session driver, a database error gives a 500.redirectTois not used withoptional: true. The default (optional: false) does not change. - New
GuestMiddleware(guard:, redirectTo:): lets only guests through, for login and register pages, like the Laravelguestmiddleware. A logged-in user goes toredirectTo, or gets a 403 (already_logged_in). - New, opt-in: access tokens, like AdonisJS access tokens or Laravel Sanctum. Session and JWT guards do not change.
- New
AccessTokenAuthDriver. A token looks likeoat_<id>.<secret>. The table keeps only a SHA-256 hash of the secret, checked in constant time. The plain token is shown once. - New
AccessTokenTables.up(schema)anddown(schema)for a migration. The default table isauth_access_tokens.tokenable_idis an unsigned big int.stringIds: true(on the table and the driver) makes it text, for users with text ids (compared exactly). For uuid users, useuuidIds: trueinstead (see below).usersTable:adds a foreign key with cascade delete (usersKey:for a key that is notid). There is an index onexpires_at. - Each token has a
type(default: the guard name, orAccessTokenAuthDriver(type: ...)). A token works only on a guard with the same type. - The time columns are
DATETIMEon MySQL, so a token can expire after 2038. - New
Auth().createAccessToken(user, name:, abilities:, expiresIn:),accessTokens(user),revokeAccessToken(user, id),revokeAllAccessTokens(user),pruneExpiredAccessTokens(),tokenCan(ability)andcurrentAccessToken. Auth().attempt(credentials)gives an access token with this driver.Auth().revokeToken(req)revokes the access token of the request.- A bad, wrong, expired or revoked token gives no user (401). A database error does too, and it is reported.
Auth().userFromToken(token)also checks an access token, for code with no request (like Socket.IO). ThencurrentAccessTokenandtokenCanwork. The driver method ischeck(token, guard)(an instance method).AccessTokenTables.up(schema, uuidIds: true)andAccessTokenAuthDriver(uuidIds: true):tokenable_idis a uuid column, so a foreign key to uuid users works on Postgres. A uuid is kept and compared in lower case.- The user must be a model of the guard.
createAccessToken,accessTokens,revokeAccessTokenandrevokeAllAccessTokensthrow anArgumentErrorfor a user of another model (eg. an admin on the users guard). - Two
Authorizationheaders give no user (401), not an error. - A token
nameover 255 characters throws anArgumentError, before anything is written. - A failed
last_used_atwrite is reported, and the request goes on.
- New
- New:
dox auth:tokens-tablewrites a migration for the access tokens table indb/migration. It callsAccessTokenTables.upandAccessTokenTables.down. Flags:--uuid,--string-ids,--users-table=<table>and--users-key=<column>. It does not overwrite: when acreate_access_tokens_tablemigration is already there, it prints so and exits with code 1. It is a package command (dox: commands:in pubspec.yaml), so it needs adoxCLI that finds package commands. The same flag twice is an error: it writes nothing and exits with code 1.--users-keywithout--users-tableprints a warning (it does nothing alone). - Needs dox_core with
package:dox_core/command.dart. - New
AuthDriver.reportError(error, stackTrace): the JWT driver now uses it to report errors. - New dependency:
crypto. - By default a JWT holds the same data as in 3.0.2: the user (
toJson(), hidden fields left out), plusiat,expand a newjti. A front end that reads user fields from the token still works. - Security, opt-in:
JwtAuthDriver(minimalPayload: true)puts only the user id (thesubclaim) in new tokens. This is the safer choice: anyone can read a JWT payload, and a small token is cheaper to send. Load the user withreq.auth?.user<User>(), not from the token. - The user id comes from the primary key, like in 3.0.2. Only a small token (a
jtiand no primary key) readssub. A user column namedsub(eg. from an OAuth login) is never taken as the id. - Tokens made before this version (no
jti) work exactly like in 3.0.2. - Security, opt-in: JWT revocation with
JwtAuthDriver(revocation: true). Off by default: thenverifyTokendoes no cache read, like in 3.0.2.- New
Auth().revokeToken(req): a JWT logout. It revokes the bearer token of the request until it expires, also afteruserFromTokenon the sameAuth. - New
Auth().revokeAllTokens(id): all tokens of the user made before the current second stop working (eg. after a password change or a ban).iatis in whole seconds, so a token made in the same second as the call still works. An old token with aniatclaim is stopped too (tokens fromJwtAuthDriverhave one). An old token with noiatworks until it expires. - New
Auth().forgetUser(id): drops the user from theuserCacheTtlcache on all isolates and servers that share the cache. - With revocation off, these three methods throw a
StateError, so no one thinks a token is revoked when it is not. revokeTokenon an old token (nojti) does nothing: it can not go on the deny-list.- New optional
JwtAuthDriver(revocationStore: ...)picks the cache store. Give auth its own store and never flush it: a flush, or a fullmemorystore withmax_size, brings revoked tokens back. Use a shared store likerediswith many isolates or servers. - With revocation on,
verifyTokenreads this store on every request, also withuserCacheTtl. On the defaultfilestore this is 2 or 3 file reads per request. Usememoryfor one isolate, orredisfor many. If the store can not be read, the token is checked like in 3.0.2 (signature andexp), and a warning is printed once, so a cache outage does not log everyone out.
- New
- New
Auth(guard: 'api').userFromToken(token): checks a JWT with no request, for example in a Socket.IOfindUser. It runs the same checks as aBearerheader (signature, algorithm, guard,exp, revocation) and uses the same code. WithuserCacheTtlon, a deleted or banned user is still found until the cache time ends, unlessforgetUserruns. A null, bad, expired, revoked or changed token gives null. Needs a guard withJwtAuthDriver. The driver method isJwtAuthDriver.userFromToken(token, guard). - New
Auth(guard: 'web').userFromSession(session): the user that is logged in to a session, with no request. Load the session withSessionMiddleware().fromCookie(value)of dox_core. Needs a guard withSessionAuthDriver. The driver method isSessionAuthDriver.userFromSession(session, guard). Auth().logout(req)is not changed: it is the session logout, like in 3.0.2.- Fix: the
Bearerprefix of theAuthorizationheader is matched in any case, sobearer xyzworks. NewJwtAuthDriver.bearerToken(req)reads the token. - Fix: JWT
verifyTokenno longer hides unexpected errors. A database outage or a bad config still gives no user (a 401), like in 3.0.2, but the error now goes toAppConfig.exceptionHandler.report(or stderr before Dox is set up), so you can see it. A bad, changed or expired token is still quiet. - Fix: a request with two
Authorizationheaders is a normal 401 for the JWT and access token drivers. It is no longer reported as an error, so it does not fill the error tracker.JwtAuthDriver.bearerToken(req)gives null for it. - Security, opt-in: login throttle.
Auth.throttle = LoginThrottle(maxAttempts: 5, decay: Duration(minutes: 1))limits failedattemptandattemptSessionlogins per login field and ip, with the app cache. Too many tries throwLoginThrottledException(429).attemptSessionalso sendsRetry-After. Off by default, so nothing changes. New optionalAuth(ip: req.ip())gives the ip toattempt. - New:
Auth.needsRehash(hash)is true when a password hash was not made with the cost ofHash.rounds(orrounds:).Auth.hashCost(hash)reads the cost of a hash. The default cost stays 10. The README shows how to raise it and hash old passwords again on login. AuthDriver.createTokengetsuser.toJson(), like in 3.0.2. When the primary key is hidden, the id is added assub.
3.0.2 #
- New: gates and policies, for what a user may do.
Gate.define('update-post', (User user, Post post) => ...)adds a rule. The user and subject types come from the function.Policy<User, Post>holds the rules of one model. Add it withGate.policy<Post>(PostPolicy()).Gate.allows,denies,authorize(403 when denied),inspect,anyandall.Gate.beforeandGate.afterhooks.Policy.beforefor one policy.GateResponse.deny('reason')gives the message of the 403.- A guest is denied, unless the user type is nullable.
req.can,req.cannotandreq.authorizeuse the user ofreq.auth.Can('update', param: 'post')middleware. A guest gets 401, a denied user gets 403. Withparam, the subject is theRoute.bindvalue.
3.0.1 #
JwtAuthDriverkeeps old tokens working after anAPP_KEYchange. When a token has a wrong signature, it tries each old key fromAppConfig.previousKeys. New tokens are signed with the current key only. An expired token or a bad claim still fails at once.- New
previousSecretsoption onJwtAuthDriver, for a JWT secret that is notAPP_KEY. - Needs dox_core 3.0.1.
3.0.0 #
- The first stable release.
- The package now lives in its own repo: dartondox/dox-auth. Nothing changes for users: same package name, same API.
3.0.0-rc.1 #
- Breaking:
JwtAuthDriverno longer signs with theSecretKeytext as it is. The HMAC key is made from it with HKDF-SHA256 and the labeldox:jwt. Existing tokens become invalid after this version. Users must log in again.driver.signingKeygives the key, for another service that checks the tokens. - Security:
JwtAuthDriver.verifyTokenaccepts only the configuredalgorithm. A token with another algorithm in its header is rejected. - Security:
attemptonly puts a string or a number into the user query. A map or a list as the email (or another identifier) fails the login. AuthMiddlewareandAuth.setUsersetreq.authdirectly. They no longer put the auth into the request input.UnAuthorizedExceptiontakes adynamic message, so a map message works.APP_ENV=testingis treated liketestfor the short secret check: only a warning.
3.0.0-alpha.17 #
- Uses dox_orm 3.0.0-alpha.12.
3.0.0-alpha.16 #
- Version bump only, to match the other packages.
3.0.0-alpha.15 #
- Docs: the README and the example set up auth in an
AppAuthProviderthat extendsDoxProvider.
3.0.0-alpha.14 #
- New:
Auth().setUser(req, user)sets the logged-in user onreq.auth, with no token and no password check. Use it in your own auth middleware, like an API key check. - Docs: how to write a custom guard. Extend
AuthDriver, return the user fromverifyToken, and useAuthMiddleware(guard: 'api'). The README and the authentication page show an API key example. - Fix: importing
dox_authanddox_coretogether gave an "ambiguous import" error forAUTH_REQUEST_KEY.dox_authno longer has its own copy. The one indox_coreis used.
3.0.0-alpha.13 #
- Version bump only, to match the other packages.
3.0.0-alpha.12 #
- New:
SessionAuthDriverkeeps the login in the session, for web pages. UseAuth().attemptSession(req, credentials),Auth().loginSession(req, user)andAuth().logout(req). Login and logout give the session a new id. NeedsSessionMiddleware. - New:
AuthMiddleware(redirectTo: '/login')sends a guest to that page instead of a 401. - Docs: with the default
cookiesession driver, an old copy of the cookie still works after logout. The README now says to use thecachedriver when logout must end old cookies. - Change: the password check of
attemptmoved toAuthDriver.checkCredentials, so all drivers share it.
3.0.0-alpha.11 #
- Version bump only, to match the other packages.
3.0.0-alpha.10 #
- Version bump only, to match the other packages.
3.0.0-alpha.9 #
- Version bump only, to match the other packages.
3.0.0-alpha.8 #
- Security: a JWT secret (
SecretKey) shorter than 32 bytes stops the app with anArgumentErrorwhenAPP_ENVis notdevelopment,localortest. In those envs it prints one warning line. Make a key withdox key:generateoropenssl rand -hex 32. Hashnow comes fromdox_core. dox_auth had its own copy.package:dox_auth/src/hash.dartre-exports it. No change in behaviour. dox_auth now depends on dox_core.
3.0.0-alpha.7 #
- Perf:
attemptruns bcrypt in another isolate (Isolate.run). Before, each login blocked the server isolate for the whole hash. - Perf: the dummy hash for unknown users is made when the driver is created, in another isolate. Before, the first login paid for two hashes.
- New:
JwtAuthDriver(hashRounds: 10). Set it to the bcrypt cost of your stored hashes. - New:
JwtAuthDriver(userCacheTtl: ...). Keeps the user of a token in memory for this time, soverifyTokendoes not runfind(id)on every request. Off by default. - Security:
JwtAuthDriverthrowsArgumentErrorwhen theSecretKeyis empty. Before, an app with noAPP_KEYsigned tokens with an empty key, so anyone could make a token for any user. - Security:
attemptruns bcrypt also when no user is found, or when the user has no password. Before, an unknown email answered much faster than a wrong password, so the time told which emails have an account.
3.0.0-alpha.6 #
- Version bump only, to match the other packages.
3.0.0-alpha.5 #
- Breaking:
JwtAuthDriver.expiresInis 1 hour by default. Before, it wasnull, and tokens never expired. - New: named guards work. Use
Auth(guard: 'admin')andAuthMiddleware(guard: 'admin'). Before, onlydefaultGuardwas used. - A token keeps its guard name in the
audclaim. A token from one guard does not work on another guard. verifyTokenchecks theissclaim whenissueris set.- Breaking:
AuthDrivermethods get the guard name as a new parameter.AuthEngine().guard(name)replacesAuthEngine().driverandAuthEngine().provider.
3.0.0-alpha.4 #
- Version bump only, to match the other packages.
3.0.0-alpha.3 #
- Version bump only, to match the other packages.
3.0.0-alpha.2 #
- Needs Dart 3.13 or newer.
- All dependencies updated to their latest versions.
dart_jsonwebtoken3.4 (pointycastle4).
3.0.0-alpha.1 #
- Version 3 of Dox. All Dox packages now share one version.
- Needs Dart 3.6 or newer.
- See the release notes for all main changes.
- Uses
dox_orm(wasdox_query_builder). dart_jsonwebtoken3.
2.0.0 #
- Compatible for core version 2.0.
1.0.1 #
- Initial version.