Skip to content

How to access logged-in user data #127

@JayGajjar

Description

@JayGajjar

I am currently running feathers v4, and using custom JWTStrategy to add user role into JWT token. With this implementation i am unable to access authenticated web-services.
Is there any way to get permission with default JWTStrategy ?

Please check my code

authentication.js

const { AuthenticationService, JWTStrategy } = require('@feathersjs/authentication');
const { LocalStrategy } = require('@feathersjs/authentication-local');
const { expressOauth } = require('@feathersjs/authentication-oauth');

class LegacyAuthenticationService extends AuthenticationService {
  async getPayload(authResult, params) {
    // Call original `getPayload` first
    const payload = await super.getPayload(authResult, params);
    const { user } = authResult;

    if (user && user.roles) {
      payload.roles = user.roles;
    }

    return payload;

  }
}

class LegacyJWTStrategy extends JWTStrategy {
  getEntityId(authResult) {
    const { authentication: { payload } } = authResult;

    return payload.roles || payload.sub;
  }
}

module.exports = app => {
  const authentication = new LegacyAuthenticationService(app);

  authentication.register('jwt', new LegacyJWTStrategy());
  authentication.register('local', new LocalStrategy());

  app.use('/authentication', authentication);
  // app.configure(expressOauth());
};

`

users.hooks.js

`const { authenticate } = require('@feathersjs/authentication').hooks;

const {
  hashPassword, protect
} = require('@feathersjs/authentication-local').hooks;

module.exports = {
  before: {
    all: [],
    find: [ authenticate('jwt') ], 
    get: [ authenticate('jwt') ], <--- This function is unable to decode custom JWT
    create: [ hashPassword('password') ],
    update: [ hashPassword('password'),  authenticate('jwt') ],
    patch: [ hashPassword('password'),  authenticate('jwt') ],
    remove: [ authenticate('jwt') ]
  },

  after: {
    all: [ 
      // Make sure the password field is never sent to the client
      // Always must be the last hook
      protect('password')
    ],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: []
  },

  error: {
    all: [],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: []
  }
};
`

Error

GET Api Url: http://localhost:3030/users

{"name":"BadRequest","message":"Cast to ObjectId failed for value "admin" at path "_id" for model "users"","code":400,"className":"bad-request","errors":{}}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions