You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
How to know which strategy was used by fastify-auth?聽#1083
However, my endpoints should respond differently to the request depending on which of the two strategies was used.
So, in my request handler, how can I know if fastify-auth authenticated the request with bearer auth or as anonymous?
awaitfastify.register(auth).register(bearerAuthPlugin,{addHook: false, keys,verifyErrorLogLevel: 'debug'}).decorate('allowAnonymous',function(req,reply,done){if(req.headers.authorization){returndone(Error('not anonymous'))}returndone()})fastify.route({method: 'GET',url: '/multiauth',preHandler: fastify.auth([fastify.allowAnonymous,fastify.verifyBearerAuth]),handler: function(req,reply){if(AUTHWASBEARER){// <--- How to make this check?reply.send({auth: 'bearer'})}else{reply.send({auth: 'anonymous'});}}})
// server.jsconstfastify=require('fastify')({logger: true});constauth=require('@fastify/auth');constbearerAuthPlugin=require('@fastify/bearer-auth');// 1. Define the secret keys for bearer auth// The token 'my-secret-token' is the only valid key.constkeys=newSet(['my-secret-token']);// 2. Custom verification function for fastify-bearer-auth// This function explicitly sets req.authData upon successful verification.asyncfunctionverifyKeyAndSetUser(key,req){// Log the key received for debuggingreq.log.info({received_key: key},'Bearer Auth received key');if(keys.has(key)){// SUCCESS: Explicitly set the authenticated user data on the request.// This is the key fix for the multi-auth chaining issue.req.authData={id: key,role: 'authenticated_user',token_used: true};// Return true to indicate successful authentication.returntrue;}// Return false if rejectedreturnfalse;}asyncfunctionroutes(fastify,options){// 3. Register the pluginsawaitfastify.register(auth).register(bearerAuthPlugin,{addHook: false,// Don't auto-hook the route, let fastify.auth handle itauth: verifyKeyAndSetUser,// Use the custom verification functionverifyErrorLogLevel: 'debug'})// 4. Custom decorator for anonymous access.decorate('allowAnonymous',function(req,reply,done){if(req.headers.authorization){// If an Authorization header is present, fail this strategy by returning an Error.// This forces fastify.auth to move on to the next strategy (verifyBearerAuth).returndone(newError('Auth header present, check bearer auth.'))}// If no Authorization header, succeed and mark request as anonymous.req.isAnonymous=true;returndone()})// 5. Define the route with the multi-auth preHandlerfastify.route({method: 'GET',url: '/multiauth',preHandler: fastify.auth([fastify.allowAnonymous,fastify.verifyBearerAuth]),handler: function(req,reply){// 6. Check the explicit flags in the handler// Check for Bearer Auth success (highest priority)if(req.authData){reply.send({auth_strategy: 'bearer',user_data: req.authData});}elseif(req.isAnonymous){// Check for Anonymous successreply.send({auth_strategy: 'anonymous'});}else{// Fallback (should ideally be unreachable if fastify.auth works)reply.code(401).send({error: 'Auth failed unexpectedly'});}}});}fastify.register(routes);// 7. Start the serverconststart=async()=>{try{awaitfastify.listen({port: 3000});console.log(`Server listening on http://localhost:3000`);}catch(err){fastify.log.error(err);process.exit(1);}};start();
Activity
pckrishnadas88 commentedon Dec 3, 2025