nearform / fastify-auth0-verify Goto Github PK
View Code? Open in Web Editor NEWAuth0 verification plugin for Fastify
Auth0 verification plugin for Fastify
Hi Team,
Thank you for your contribution on creating the plugin for Auth0.
I was able to add plugin to verify but is there any method to implement custom login using the plugin?
Hi!
v0.4.1 is available on GitHub releases(/git tag), but only 0.4.0 is available via npm.
Can you please push 0.4.1 to npm?
Thanks!
Unreleased commits have been found which are pending release, please publish the
changes.
Issue generated by
github-actions-notify-release.
Unreleased commits have been found which are pending release, please publish the changes.
Issue generated by github-actions-notify-release.
Unreleased commits have been found which are pending release, please publish the changes.
Issue generated by github-actions-notify-release.
Based on the following commits, a patch release is recommended.
Unreleased commits have been found which are pending release, please publish the changes.
Issue generated by github-actions-notify-release.
Unreleased commits have been found which are pending release, please publish the changes.
Issue generated by github-actions-notify-release.
It would be helpful if a Typescript import syntax example and how to use is shown.
Line 32 in a05a02d
Line 7 in 4d1e1f5
Does this library suffer from not handling timeouts like the web browser version (whatwg/fetch#20)? Might it be better to use a Node native module like got
?
fastify-auth0-verify/README.md
Line 42 in 4d1e1f5
This options
is not defined in the example. Shouldn't the example be copy and paste-able as-is?
The current code is asking the remote secret for every request: this is going to be expensive for production systems, and possibly unneeded.
Do we know how much time it is valid for?
Can we cache it?
In
Line 112 in a05a02d
You can just attach a statusCode of 500 instead of wrapping the exception. This will not remove the stacktrace.
Hi! I am working on a Next.js SPA which talks to a backend API written in Fastify. I'm using the nextjs-auth0 library to store the JWT in a cookie which is also sent to the API. However, once the JWT expires, fastify-jwt library causes requests to fail by throwing "Authorization token expired." According to the maintainers of nextjs-auth0, it is safe to ignore the exp value: auth0/nextjs-auth0#538. So my users are logged into the next.js app, and able to retrieve their profiles, but the API endpoint is not able to validate their requests any longer. Is there a way for me to override the rule in fastify-jwt that a jwt must not have expired? I know that sounds kind of crazy, but it would be much more work for me to refresh the token on my own.
You can see how I am using the next.js library to extract the token from the request so this library can pick it up:
import { initAuth0 } from '@auth0/nextjs-auth0';
const auth = initAuth0();
app.register(require('fastify-auth0-verify'), {
domain: process.env.AUTH0_ISSUER_BASE_URL,
secret: process.env.AUTH0_SECRET,
extractToken: (request: any) => {
const session = auth.getSession(request, {} as any);
return session?.idToken;
}
});
Any guidance on how I should be approaching this is helpful. Thanks!
Based on the following commits, a minor release is recommended.
Unreleased commits have been found which are pending release, please publish the changes.
Issue generated by github-actions-notify-release.
Hello,
I am unsure how this should be filed. I would like to suggest something for consideration.
In my opinion, It would be awesome if README.md or another document included jest mocking examples. There are mocks included with the sources, yet no good examples for developers writing tests for routes utilizing your library and authenticate
.
Thank you.
Unreleased commits have been found which are pending release, please publish the changes.
Issue generated by github-actions-notify-release.
Based on the following commits, a patch release is recommended.
Unreleased commits have been found which are pending release, please publish the changes.
Issue generated by github-actions-notify-release.
fastify-auth0-verify/index.d.ts
Line 64 in 60752d5
Currently this type shows an error since the decode
function expects a string as the first param. It should be something like this, which is similar to how fastify-jwt declares it's functions:
import type { DecodeOptions } from "jsonwebtoken"
type JWTDecodedType = Record<string, unknown> | string
# ...
jwtDecode<Decoded extends JWTDecodedType>(options?: DecodeOptions): Decoded
Unreleased commits have been found which are pending release, please publish the changes.
Issue generated by github-actions-notify-release.
Unreleased commits have been found which are pending release, please publish the changes.
Issue generated by github-actions-notify-release.
The fastify-jwt library, which is used in this project, has an option to define the name of the JWT cookie (see https://github.com/fastify/fastify-jwt#example-using-cookie). This cookie is used to get the JWT, if no Authorization header is provided.
I would like to have this option in fastify-auth0-verify as well. I think would be easy to implement - I could create a PR for this. WDYT?
As titled
Would that be interesting to have a formatUser
optional property when registering this plugin to configure @fastify/jwt
under the hoods? I could try to provide a PR for such.
โ UPDATE: this request already has a PR, the plan is described in this comment in the PR. Please follow that plan to complete this change.
I've just checked the code and can't really see how it's specific to Auth0. It just looks like a spec-compliant package so it should work with any spec-compliant id server as far as I can see (the main spec here being RFC7517 or JWK). Right?
I'm considering using this package on an open source API server, and I don't want operators to be tied to Auth0, which is why I wanted to check.
Add Notify Twitter
workflow that will push a tweet to @NearFormOSS upon successful release.
Unreleased commits have been found which are pending release, please publish the changes.
Issue generated by github-actions-notify-release.
Based on the following commits, a minor release is recommended.
Unreleased commits have been found which are pending release, please publish the changes.
Issue generated by github-actions-notify-release.
Unreleased commits have been found which are pending release, please publish the changes.
Issue generated by github-actions-notify-release.
Thanks for creating this library! I just added it to my API to verify auth0 tokens and running into an issue with jest:
Jest has detected the following 1 open handle potentially keeping Jest from exiting:
โ DNSCHANNEL
at new CacheableLookup (node_modules/cacheable-lookup/source/index.js:75:14)
at Object.<anonymous> (node_modules/fastify-auth0-verify/node_modules/got/dist/source/core/index.js:32:24)
at Object.<anonymous> (node_modules/fastify-auth0-verify/node_modules/got/dist/source/as-promise/types.js:14:16)
Implementation is as described in the readme:
app.register(require('fastify-auth0-verify'), {
domain: auth0.domain,
audience: auth0.audience,
secret: auth0.clientSecret
})
route:
module.exports = function (fastify, opts, next) {
fastify.route({
method: 'GET',
url: '/',
preValidation: fastify.authenticate,
schema: {
query: querySchema,
response: {
200: bodySerialization
}
},
handler: async (request, reply) => {})
next()
}
test.js
const fastify = require('../../../app')
const { agent } = require('../../auth')
let token
beforeAll(async () => {
token = await agent()
})
afterAll(() => {
fastify.close()
})
describe('GET /', () => {
it('should return', async () => {
const response = await fastify.inject({
method: 'GET',
headers: {
Authorization: `Bearer ${token}`
},
url: '/'
})
expect(response.statusCode).toEqual(200)
})
})
When implementing and testing the package in our project an unexpected error response & statuscode was observed.
I tried a few different use cases to observe what the application would be returning.
When sending a basic dummy jwt token taken from jwt.io looking like this.
// Header
{
"alg": "HS256",
"typ": "JWT"
}
// Payload
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}
It responds with the object below which is a perfectly valid response. (note no kid
is present in the request token header here)
{
"statusCode": 401,
"error": "Unauthorized",
"message": "Authorization token is invalid: secret or public key must be provided"
}
I then sent a token that contained my regular auth0 domain as the issuer while the app was registered with my custom domain as the issuer.
The token looked like this
// Header
{
"alg": "RS256",
"typ": "JWT",
"kid": "<kid>"
}
// Payload
{
"iss": "https://<tenant>.eu.auth0.com/",
"sub": "<subject>",
"aud": "<api audience>,
"iat": 1618481452,
"exp": 1618567852,
"azp": "<party>",
"gty": "client-credentials"
}
The response was the object below, again a valid response (a bit more info as to why the token was invalid might've been nice but was pretty easily found by adding some log statements to the file)
{
"statusCode": 401,
"error": "Unauthorized",
"message": "Invalid token."
}
However this is the part where it get's weird. When sending a request to the API using a token granted by a different tenant like the one posted below.
// Header
{
"alg": "RS256",
"typ": "JWT",
"kid": "<kid>"
}
// Payload
{
"iss": "<other tennant>",
"sub": "<subject>",
"aud": "<other api audience>,
"iat": 1618230875,
"exp": 1618317275,
"azp": "<party>",
"gty": "client-credentials"
}
The response given is
{
"statusCode": 500,
"error": "Internal Server Error",
"message": "Something went wrong"
}
and the log saying No matching key found in the set. Error: No matching key found in the set.
From looking at what's happening it seems like it goes and searches the domain specified in the app.register(fastifyAuth0Verify, {})
for a key with the kid
from the token header.
However as this kid
will not be present in the <domain>/.well-known/jwks.json
it is unable to find a key.
in the index.js
file this snippet can be found
if (!key) {
// Mark the key as missing
cache.set(cacheKey, null)
throw new Error(errorMessages.missingKey)
}
key will in fact be undefined as the jwks.json
does not contain a key with the specified kid
. The throw error causes it to go into the error handling. Which in turn sets the status to 500 and throws the InternalServerError
catch (e) {
if (e.response) {
throw InternalServerError(`${errorMessages.jwksHttpError}: [HTTP ${e.response.status}] ${JSON.stringify(e.body)}`)
}
e.statusCode = 500
throw e
}
InternalServerError does not seem fitting here as it is not unclear as to why the request can't be fulfilled as there is no private or public key available.
A more appropriate response here would be a 401
as the request itself was valid, just the token used is not authorized for this API.
When testing the same flow against the express-jwt package used in a different project it returns a 401
with the following message: UnauthorizedError: secret or public key must be provided
.
This is the behaviour I would expect from this flow as well.
Is there a chance of this being improved upon as a more appropriate response would be appreciated.
Based on the following commits, a minor release is recommended.
Unreleased commits have been found which are pending release, please publish the changes.
Issue generated by github-actions-notify-release.
Unreleased commits have been found which are pending release, please publish the changes.
Issue generated by github-actions-notify-release.
I came across some outdated and/or incorrect types, creating this issue to link some PRs to it. What's missing is the type definition for cookie
and the support for string[]
as issuer.
Unreleased commits have been found which are pending release, please publish the changes.
stale-days
have passed.Issue generated by github-actions-notify-release.
Unreleased commits have been found which are pending release, please publish the changes.
Issue generated by github-actions-notify-release.
import auth0Verify from 'fastify-auth0-verify';
server.register(auth0Verify, {
domain: "...",
});
Yields this warning:
FastifyDeprecation: You are decorating Request/Reply with a reference type. This reference is shared amongst all requests. Use onRequest hook instead. Property: auth0Verify
Anyone following the readme and using:
"fastify": "^3.2.1",
Might encounter this.
Unreleased commits have been found which are pending release, please publish the changes.
Issue generated by github-actions-notify-release.
The dependabot
tried to update the library to use the latest version of fastify-jwt
v4 but was unsuccessful. The main issue is that the token verification process is not compatible with the fast-jwt
verify
method.
This issue needs to be investigated if it is possible to solve within this library or the fix needs to be done on fast-jwt
.
If the issue is fixed in fast-jwt
library that will require release of fastify-jwt
as well.
Check if it is possible to replace the Node-Cache
with the internal caching of fastify-jwt
Hey fastify / nearform team. Just gave this a try from my custom jwt setup and it works great.
The only thing missing is the ability to have multiple issuers or audiences in the verification process. It this open for implementation? Is in place with fastify-jwt
Use case should be clear, but for example I have an API with this verification logic in it, but I have several auth0 clients that speak to it. Or I have an admin api that I use for impersonation that forces the client_id as the audience.
My previous setup was:
const FastifyJWT = require("fastify-jwt");
const JwksRsa = require("./util/jwks.js");
...
fastify.register(FastifyJWT, {
secret: JwksRsa({
cache: true,
rateLimit: false,
jwksRequestsPerMinute: 100, // Default value
cacheMaxEntries: 50, // Default value
cacheMaxAge: Ms("10h"), // Default value
jwksUri: Config.auth.jwksUri
}),
verify: {
algorithms: ["RS256"],
audience: Config.auth.audience,
issuer: [`https://${Config.auth.domain}/`, `https://${Config.auth.domain2}/`]
},
decode: {
complete: true
}
});
And now:
const FastifyAuth0Verify = require("fastify-auth0-verify")
...
fastify.register(FastifyAuth0Verify, {
secret: Config.auth.clientSecret,
domain: `https://${Config.auth.domain}/`,
audience: Config.auth.audience,
secretsTtl: 10 * 60 * 60 * 1000 // 10hr
})
So the only real feature missing here is the array of issuers and audiences.
Minor update - the message should contain a tag #fastifyjs and @fastifyjs
Unreleased commits have been found which are pending release, please publish the changes.
Issue generated by github-actions-notify-release.
Unreleased commits have been found which are pending release, please publish the changes.
Issue generated by github-actions-notify-release.
The release fails with the following error:
Error: Unable to publish to npm: npm publish --otp 720449 --tag latest returned code 127 and signal null
STDOUT:
> [email protected] prepublishOnly
> npm run ci
> [email protected] ci
> npm run lint && jest --coverage --ci --coverageReporters=json && tsd
> [email protected] lint
> eslint index.js test.js
STDERR: sh: 1: eslint: not found
npm ERR! code 127
npm ERR! path /home/runner/work/fastify-auth0-verify/fastify-auth0-verify
npm ERR! command failed
npm ERR! command sh -c npm run ci
npm ERR! A complete log of this run can be found in:
npm ERR! /home/runner/.npm/_logs/2022-04-07T15_14_25_952Z-debug-0.log
The reason is that npm install
is not run before running npm run ci
step. To solve this issue a custom build step needs to be added to the release workflow.
Based on the following commits, a minor release is recommended.
Unreleased commits have been found which are pending release, please publish the changes.
Issue generated by github-actions-notify-release.
Based on the following commits, a minor release is recommended.
Unreleased commits have been found which are pending release, please publish the changes.
Issue generated by github-actions-notify-release.
We have a pending release to do which, among other things, includes the v2 major of fast-jwt.
Let's figure out what impact that has on this package and plan the next release accordingly.
See #243
On the Auth0 website it says:
API to accept RS256 signed tokens
and I have my app configured to use RS256 and see the alg
as RS256 in the well known keys response; however, when I send a request with token to the endpoint /verify
from the sample.
I see the Authorization header such as: Authorization: Bearer YxEyRxe6DtnO_9FWVP_sTkATVFyyXI91
This YxEyRxe6DtnO_9FWVP_sTkATVFyyXI91
doesn't look correct to me, I expected something like eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Is this token in the correct expected format for this plugin to verify it?
I'm thinking it is not in RS256 which is why it keeps returning 401 invalid.
I do see the proper format of id_token
when fetching from the /token endpoint but the access_token
seems wrong.
I'm assuming Auth0 is configured by default to be correct and somehow I have fastify-auth0-verify
plugin misconfigured. I have the domain
and audience
configured and thought it whould work by default with the types of tokens Auth0 issues.
Any ideas?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.