Oak middleware for JWT
MIT License
Oak middleware for JWT using Djwt
As an application middleware
import { jwtMiddleware } from "https://raw.githubusercontent.com/halvardssm/oak-middleware-jwt/master/mod.ts";
import { Middleware } from "https://deno.land/x/oak/mod.ts";
const app = new Application();
app.use(jwtMiddleware<Middleware>({ key: "foo" }));
await app.listen(appOptions);
As a router middleware
import { jwtMiddleware, OnSuccessHandler } from "https://raw.githubusercontent.com/halvardssm/oak-middleware-jwt/master/mod.ts"
import { RouterMiddleware } from "https://deno.land/x/oak/mod.ts";
interface ApplicationState {
userId: string
}
const router = new Router();
const app = new Application<ApplicationState>();
const onSuccess: OnSuccessHandler = (ctx, jwtPayload) => {
ctx.state.userId = jwtPayload.userId
}
router
.get("/bar", jwtMiddleware<RouterMiddleware>({ key:"foo", onSuccess }), async (ctx) => {
const callerId = ctx.state.userId
...
})
app.use(router.routes());
await app.listen(appOptions);
With ignore patterns
import {
IgnorePattern,
jwtMiddleware,
OnSuccessHandler,
} from "https://raw.githubusercontent.com/halvardssm/oak-middleware-jwt/master/mod.ts";
import { RouterMiddleware } from "https://deno.land/x/oak/mod.ts";
const app = new Application<ApplicationState>();
const ignorePatterns: IgnorePattern[] = ["/baz", /buz/, {
path: "/biz",
methods: ["GET"],
}];
app.use(jwtMiddleware<Middleware>({ key: "foo", ignorePatterns }));
await app.listen(appOptions);
/authenticate
, can be a RegExp, Pattern object or string. When passing a===
All errors originating from this middleware is of class JWTMiddlewareError
which is exported. To handle JWTMiddlewareError
s you can do such:
...
} catch(e){
if(e instanceof JWTMiddlewareError){
//do something
}
}
algorithm
parameter's type from Algorithm
toAlgorithmInput
import { AlgorithmInput } from "https://raw.githubusercontent.com/halvardssm/oak-middleware-jwt/master/mod.ts";
const algorithm: AlgorithmInput = "HS512";
app.use(jwtMiddleware<Middleware>({ key: "foo", algorithm }));
onSuccess
gets an object of type Payload
as a second argument (checkonFailure
gets an object of type Error
as a second argument, shouldtrue
if the error should be thrown instead of returning as aconst onFailure = (ctx, error: Error) => {
console.log(error.message);
};
const onSuccess = (ctx, payload: Payload) => {
console.log(payload.userId);
};
onFailure
callback) if the token sent is expired. Can cause problems inAll contributions are welcome, make sure to read the contributing guidelines.