在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:koajs/jwt开源软件地址:https://github.com/koajs/jwt开源编程语言:JavaScript 100.0%开源软件介绍:koa-jwt
Table of ContentsIntroductionThis module lets you authenticate HTTP requests using JSON Web Tokens in your Koa (node.js) applications. See this article for a good introduction.
Installnpm install koa-jwt UsageThe JWT authentication middleware authenticates callers using a JWT
token. If the token is valid, Retrieving the tokenThe token is normally provided in a HTTP header ( /**
* Your custom token resolver
* @this The ctx object passed to the middleware
*
* @param {Object} opts The middleware's options
* @return {String|null} The resolved token or null if not found
*/ opts, the middleware's options:
The resolution order for the token is the following. The first non-empty token resolved will be the one that is verified.
Passing the secretOne can provide a single secret, or array of secrets in Checking if the token is revokedYou can provide a async function to jwt for it check the token is revoked.
Only you set the function in /**
* Your custom isRevoked resolver
*
* @param {object} ctx The ctx object passed to the middleware
* @param {object} decodedToken Content of the token
* @param {object} token token The token
* @return {Promise} If the token is not revoked, the promise must resolve with false, otherwise (the promise resolve with true or error) the token is revoked
*/ Examplevar Koa = require('koa');
var jwt = require('koa-jwt');
var app = new Koa();
// Custom 401 handling if you don't want to expose koa-jwt errors to users
app.use(function(ctx, next){
return next().catch((err) => {
if (401 == err.status) {
ctx.status = 401;
ctx.body = 'Protected resource, use Authorization header to get access\n';
} else {
throw err;
}
});
});
// Unprotected middleware
app.use(function(ctx, next){
if (ctx.url.match(/^\/public/)) {
ctx.body = 'unprotected\n';
} else {
return next();
}
});
// Middleware below this line is only reached if JWT token is valid
app.use(jwt({ secret: 'shared-secret' }));
// Protected middleware
app.use(function(ctx){
if (ctx.url.match(/^\/api/)) {
ctx.body = 'protected\n';
}
});
app.listen(3000); Alternatively you can conditionally run the var Koa = require('koa');
var jwt = require('koa-jwt');
var app = new Koa();
// Middleware below this line is only reached if JWT token is valid
// unless the URL starts with '/public'
app.use(jwt({ secret: 'shared-secret' }).unless({ path: [/^\/public/] }));
// Unprotected middleware
app.use(function(ctx, next){
if (ctx.url.match(/^\/public/)) {
ctx.body = 'unprotected\n';
} else {
return next();
}
});
// Protected middleware
app.use(function(ctx){
if (ctx.url.match(/^\/api/)) {
ctx.body = 'protected\n';
}
});
app.listen(3000); For more information on You can also add the app.use(jwt({ secret: 'shared-secret', passthrough: true })); This lets downstream middleware make decisions based on whether If you prefer to use another ctx key for the decoded data, just pass in app.use(jwt({ secret: 'shared-secret', key: 'jwtdata' })); This makes the decoded data available as You can specify audience and/or issuer as well: app.use(jwt({ secret: 'shared-secret',
audience: 'http://myapi/protected',
issuer: 'http://issuer' })); You can specify an array of secrets. The token will be considered valid if it validates successfully against any of the supplied secrets. This allows for rolling shared secrets, for example: app.use(jwt({ secret: ['old-shared-secret', 'new-shared-secret'] })); Token Verification ExceptionsIf the JWT has an expiration ( All error codes for token verification can be found at: https://github.com/auth0/node-jsonwebtoken#errors--codes. Notifying a client of error codes (e.g token expiration) can be achieved by sending the // Custom 401 handling (first middleware)
app.use(function (ctx, next) {
return next().catch((err) => {
if (err.status === 401) {
ctx.status = 401;
ctx.body = {
error: err.originalError ? err.originalError.message : err.message
};
} else {
throw err;
}
});
}); If the This module also support tokens signed with public/private key pairs. Instead of a secret, you can specify a Buffer with the public key: var publicKey = fs.readFileSync('/path/to/public.pub');
app.use(jwt({ secret: publicKey })); If the The signature of this function should be This option can be used to support JWKS (JSON Web Key Set) providers by using node-jwks-rsa. For example: const { koaJwtSecret } = require('jwks-rsa');
app.use(jwt({
secret: koaJwtSecret({
jwksUri: 'https://sandrino.auth0.com/.well-known/jwks.json',
cache: true,
cacheMaxEntries: 5,
cacheMaxAge: ms('10h')
}),
audience: 'http://myapi/protected',
issuer: 'http://issuer'
})); Related Modules
Note that koa-jwt no longer exports the Testsnpm install
npm test Authors/Maintainers
CreditsThe initial code was largely based on express-jwt. Contributors
License |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论