Hello there :slightly_smiling_face: I was thinking...
# orm-help
m
Hello there 🙂 I was thinking about authentication and following this post from Apollo website (https://www.apollographql.com/docs/apollo-server/security/authentication/#authorization-in-resolvers) you should get user infos from token directly when the server receive a request (event if the resolver is not guarded) and following @nikolasburk exemple (https://github.com/prisma/prisma-examples/blob/latest/typescript/graphql-auth/src/permissions/index.ts) you should do it only when you need user infos but it leads to extract token data multiple times. So the question is : Which one is the better ? How do you handle this in your projects ? (For now I use the Niko approach but I'm not sure it's the right way)
r
@Mikastark 👋 This is the recommended approach via
graphql-shield
for authentication and authorisation both. There’s no performance penalty if the token is extracted multiple times. You can also use caching options to prevent the rule being called multiple times
m
Hello @Ryan 👋 I personnally use the nexus AuthorizationPlugin but I guess this is the same debate as graphql-shield. Thanks for your answer, it's reassuring. More deeply, I use an Auth class to gather all authentication and authorisation logic. Here is the code : import { AuthenticationError } from 'apollo-server' import { ExpressContext } from 'apollo-server-express' import { getUserTokenPayload } from './utils' export class Auth {   get _user_()_:_ TokenPayload | undefined {     return _getUser_(this.context)   }   _constructor_(private context_:_ ExpressContext) {}   _isAuthenticated_()_:_ boolean | AuthenticationError {     return !!this.user || new _AuthenticationError_('You are not authenticated')   } } The real reason behind my first question is : Should I extract token in constructor (called just once) or in the user getter (maybe called multiple times).
So I guess I shall just not change the code 😁
r
If the
AuthorizationPlugin
plugin supports caching, then you can easily keep the functionality in the getter as you have currently. It also depends on how many requests you will be having. If it’s not large, then you should be fine 🙂
I unfortunately do not have any experience with
AuthorizationPlugin
and only with
graphql-shield
.
m
I haven't seen any caching option on it. But my gql projects are for now very small, handling a little more token extraction wouldn't kill the server 😆. I moved from shield to
AuthorizationPlugin
one year ago. I think handling permission apart from resolvers themselves is a little bit confusing and error prone as you may forgot to add/remove a guard on project evolution
💯 1