# graphql-auth-directives

> Add authorization to your GraphQL API using schema directives.

Latest version **2.2.2** (published 2021-02-03) · Apache-2.0 license · 0 weekly downloads

> **Deprecated.** This package is deprecated.

## Install

```sh
npm install graphql-auth-directives
pnpm add graphql-auth-directives
yarn add graphql-auth-directives
bun add graphql-auth-directives
```

## Health

**Score 10/100 (F)** — status: deprecated.

Negative: deprecated.

## Facts

| | |
|---|---|
| Version | 2.2.2 |
| Published | 2021-02-03 |
| First published | 2018-10-16 |
| Weekly downloads | 0 |
| License | Apache-2.0 |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 3 |
| Unpacked size | 23.1 KB |
| Known vulnerabilities | 0 (+3 in 1 direct dependencies) |
| Install scripts | no |
| GitHub stars | 113 |
| Author | William Lyon |
| Maintainers | johnymontana |
| Keywords | GraphQL, authorization, neo4j |

## Links

- npm: https://www.npmjs.com/package/graphql-auth-directives
- Repository: https://github.com/grand-stack/graphql-auth-directives
- Homepage: https://github.com/grand-stack/graphql-auth-directives#readme
- Issues: https://github.com/grand-stack/graphql-auth-directives/issues
- npm.io page: https://npm.io/package/graphql-auth-directives

## Dependencies (3)

- [jsonwebtoken](https://npm.io/package/jsonwebtoken.md) ^8.3.0
- [apollo-errors](https://npm.io/package/apollo-errors.md) ^1.9.0
- [graphql-tools](https://npm.io/package/graphql-tools.md) ^4.0.7

## Alternatives

- [apollo-link-http-common](https://npm.io/package/apollo-link-http-common.md) — 879.0K weekly downloads
- [react-relay](https://npm.io/package/react-relay.md) — 336.8K weekly downloads
- [relay-test-utils](https://npm.io/package/relay-test-utils.md) — 181.6K weekly downloads
- [@vendure/core](https://npm.io/package/@vendure/core.md) — 14.8K weekly downloads
- [@pnpm/deps.graph-sequencer](https://npm.io/package/@pnpm/deps.graph-sequencer.md) — 13.4K weekly downloads

## Recent versions

- 2.2.2 (latest) — 2021-02-03
- 2.2.1 — 2020-08-27
- 2.2.0 — 2020-02-24
- 2.1.0 — 2019-02-28
- 2.0.0 — 2019-02-19
- 1.1.0 — 2019-02-03
- 1.0.1 — 2018-10-16
- 1.0.0 — 2018-10-16

## README

# graphql-auth-directives

[![CircleCI](https://circleci.com/gh/grand-stack/graphql-auth-directives.svg?style=svg)](https://circleci.com/gh/grand-stack/graphql-auth-directives)

Add authentication to your GraphQL API with schema directives.

## Schema directives for authorization

- [ ] `@isAuthenticated`
- [ ] `@hasRole`
- [ ] `@hasScope`

## Quick start

```sh
npm install --save graphql-auth-directives
```

Then import the schema directives you'd like to use and attach them during your GraphQL schema construction. For example using [neo4j-graphql.js' `makeAugmentedSchema`](https://grandstack.io/docs/neo4j-graphql-js-api.html#makeaugmentedschemaoptions-graphqlschema):


```js
import { IsAuthenticatedDirective, HasRoleDirective, HasScopeDirective } from "graphql-auth-directives";

const augmentedSchema = makeAugmentedSchema({
  typeDefs,
  schemaDirectives: {
    isAuthenticated: IsAuthenticatedDirective,
    hasRole: HasRoleDirective,
    hasScope: HasScopeDirective
  }
});
```

The `@hasRole`, `@hasScope`, and `@isAuthenticated` directives will now be available for use in your GraphQL schema:

```
type Query {
    userById(userId: ID!): User @hasScope(scopes: ["User:Read"])
    itemById(itemId: ID!): Item @hasScope(scopes: ["Item:Read"])
}
```

Be sure to inject the request headers into the GraphQL resolver context. For example, with Apollo Server:

```js
const server = new ApolloServer({
  schema,
  context: ({ req }) => {
    return req;
  }
});
```

In the case that the token was decoded with no errors the `context.user` will store the payload from the token

```js
me: (parent, args, context) => {
      console.log(context.user.id);
}
```

A JWT must then be included in each GraphQL request in the Authorization header. For example, with Apollo Client:

```js
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloClient } from 'apollo-client';


const httpLink = createHttpLink({
    uri: <YOUR_GRAPHQL_API_URI>
});

const authLink = setContext((_, { headers }) => {
    const token = localStorage.getItem('id_token'); // here we are storing the JWT in localStorage
    return {
        headers: {
            ...headers,
            authorization: token ? `Bearer ${token}` : "",
        }
    }
});

const client = new ApolloClient({
    link: authLink.concat(httpLink),
    cache: new InMemoryCache()
});
```

## Configure

Configuration is done via environment variables.

(required)
There are two variables to control how tokens are processed.
If you would like the server to verify the tokens used in a request, you must provide the secret used to encode the token in the `JWT_SECRET` variable. Otherwise you will need to set `JWT_NO_VERIFY` to true.

```sh
export JWT_NO_VERIFY=true //Server does not have the secret, but will need to decode tokens
```
or
```sh
export JWT_SECRET=><YOUR_JWT_SECRET_KEY_HERE> //Server has the secret and will verify authenticity
```

(optional)
By default `@hasRole` will validate the `roles`, `role`, `Roles`, or `Role` claim (whichever is found first). You can override this by setting `AUTH_DIRECTIVES_ROLE_KEY` environment variable. For example, if your role claim is stored in the JWT like this

```sh
"https://grandstack.io/roles": [
    "admin"
]
```

Set:

```sh
export AUTH_DIRECTIVES_ROLE_KEY=https://grandstack.io/roles
```

## Running Tests Locally

1. create ./test/helpers/.env
2. add relevant values
3. run the test server
```sh
npx babel-node test/helpers/test-setup.js
```
4. run the tests
```sh
npx ava test/*.js
```


## Test JWTs

Scopes: user:CRUD

~~~
key: qwertyuiopasdfghjklzxcvbnm123456
~~~

~~~
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJHUkFORHN0YWNrIiwiaWF0IjoxNTQ5MTQ1Mjk0LCJleHAiOjE2OTE3ODEzMDcsImF1ZCI6ImdyYW5kc3RhY2suaW8iLCJzdWIiOiJib2JAbG9ibGF3LmNvbSIsIlJvbGUiOiJBRE1JTiIsIlNjb3BlIjpbIlVzZXI6UmVhZCIsIlVzZXI6Q3JlYXRlIiwiVXNlcjpVcGRhdGUiLCJVc2VyOkRlbGV0ZSJdfQ.WJffOec05r8KuzW76asax1iCzv5q4rwRv9kvFyw7c_E
~~~

---
_Source: https://npm.io/package/graphql-auth-directives · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
