You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FeatherJS如何通过Hook结合AccessToken获取当前用户信息?

Fixing User Retrieval in FeatherJS REST API Hooks

Hey there, let's sort out why you're not getting the current user's info in your message service hook! The core problem here is that FeatherJS doesn't automatically parse your JWT token and inject the user into context.params.user—you need to set up the authentication middleware properly first, especially since you're using the raw REST API without the Feathers client. Here's how to fix this step by step:

1. Add the Authentication Middleware to Your Message Service

FeatherJS's authenticate hook handles validating the JWT token from the Authorization header and populating context.params.user. You must apply this hook before your custom hook in the service's hook chain to ensure the token is parsed first.

Update your message.service.js to include the authentication middleware:

const { authenticate } = require('@feathersjs/authentication').hooks;
const yourCustomHook = require('./hooks/your-custom-hook'); // Replace with your hook's file path

module.exports = {
  // Your service methods (find, create, etc.)
  hooks: {
    before: {
      // Place authenticate BEFORE your custom hook
      create: [authenticate('jwt'), yourCustomHook],
      // Add authenticate to other protected methods if needed
      update: [authenticate('jwt')],
      remove: [authenticate('jwt')]
    }
  }
};

2. Verify Your Authorization Header Format

When making REST requests, your Authorization header must follow this exact format:

Bearer <your-jwt-token>

A common mistake is omitting the Bearer prefix—this will cause the authentication middleware to fail, so double-check your request headers to ensure this is correct.

3. Manual Token Parsing (If You Need It)

If for some reason you can't use the official authenticate middleware, you can manually verify the token and fetch the user in your hook. Note that this is less recommended (the middleware handles edge cases like expired tokens automatically), but here's how to do it:

module.exports = function (options = {}) { 
  return async context => { 
    const { app } = context;
    const authHeader = context.params.headers?.authorization;

    // Validate header presence and format
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      throw new Error('Invalid or missing Authorization header');
    }

    // Extract token (remove "Bearer " prefix)
    const token = authHeader.slice(7);

    try {
      // Verify token and get payload
      const payload = await app.service('authentication').verifyAccessToken(token);
      // Fetch full user data from the users service
      const user = await app.service('users').get(payload.userId);

      // Inject user into context.params for later use
      context.params.user = user;
    } catch (error) {
      throw new Error('Invalid or expired token');
    }

    // Proceed with your original hook logic
    const text = context.data.text;
    context.data = { text, userId: context.params.user._id };
    return context; 
  }; 
};

4. Double-Check Hook Execution Order

Always ensure your custom hook runs after the authenticate hook. If your hook is registered first in the before.create array, context.params.user won't exist yet because the token hasn't been parsed. The order of hooks in the array determines execution priority—earlier hooks run first.

Once you set this up correctly, your original hook code should work as expected, and you'll see the userId field populated in your database entries.

内容的提问来源于stack exchange,提问作者Prometheus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:37:08