Friends Of AdonisFriends Of Adonis

Authorization

Authentication and Authorization are supported out of the box using @adonisjs/auth (authentication) and @adonisjs/bouncer (authorization).

You can find more information about Middlewares on the Official TypeGraphQL documentation

Secure operations

You can secure your queries to only allow authenticated users to use them by using the @Authorized decorator.

app/graphql/resolvers/recipe_resolver.ts
import Recipe from '#models/recipe'
import { Resolver, Query, Mutation, Authorized } from '@foadonis/graphql'
 
@Resolver(Recipe)
class RecipeResolver {
  @Query(() => [Recipe])
  @Authorized() 
  recipes() {
    // ...your logic
  }
 
  @Mutation(() => [Recipe])
  @Authorized() 
  createRecipe() {
    // ...your logic
  }
}

The Authorized decorator accepts Bouncer abilities allowing you to ensure your user respects specific requirements.

import Recipe from '#models/recipe'
import { Resolver, Query, Authorized } from '@foadonis/graphql'
import abilities from '#abilities/main'
 
@Resolver(Recipe)
class RecipeResolver {
  @Query(() => [Recipe])
  @Authorized(abilities.isAdmin) 
  recipes() {
    // ...your logic
  }
}

You can pass multiple abilities to @Authorized. The user will be authorized only if all of them pass.

Secure objects

The @Authorized decorator also works on fields allowing you to protect only certain fields. With the following example, only authenticated user can access the fullName and only admins can access email.

app/models/user.ts
import { ObjectType, Authorized } from '@foadonis/graphql'
import abilities from '#abilities/main'
 
@ObjectType()
export default class User {
  @Field()
  declare id: string
 
  @Field()
  @Authorized()
  declare fullName: string
 
  @Field()
  @Authorized(abilities.isAdmin)
  declare email: string
}

Access authenticated User

Using @CurrentUser

app/graphql/resolvers/recipe_resolver.ts
import Recipe from '#models/recipe'
import { Resolver, Query, CurrentUser } from '@foadonis/graphql'
 
@Resolver(Recipe)
class RecipeResolver {
  @Query(() => [Recipe])
  recipes(@CurrentUser() user: User) {
    // ...your logic
  }
}

The @CurrentUser decorator makes your operation only available to authenticated users. If you still want to allow guest, you must use the context.

Using the context

app/graphql/resolvers/recipe_resolver.ts
import Recipe from '#models/recipe'
import { HttpContext } from '@adonisjs/core/http'
import { Resolver, Query, Ctx } from '@foadonis/graphql'
 
@Resolver(Recipe)
class RecipeResolver {
  @Query(() => [Recipe])
  recipes(@Ctx() ctx: HttpContext) {
    const user = ctx.auth.getUserOrFail()
    // ...your logic
  }
}

On this page