Skip to content

Commit c4913f6

Browse files
committed
release: 2.0.0-rc.2
1 parent 0ac4077 commit c4913f6

22 files changed

+2877
-4
lines changed

CHANGELOG.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
# Changelog and release notes
22

3-
## Unreleased
3+
<!-- ## Unreleased -->
44

55
<!-- Here goes all the unreleased changes descriptions -->
66

7+
## v2.0.0-rc.2
8+
79
## Features
810

911
- support declaring middlewares on resolver class level (#620)

package-lock.json

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "type-graphql",
3-
"version": "2.0.0-rc.1",
3+
"version": "2.0.0-rc.2",
44
"private": false,
55
"description": "Create GraphQL schema and resolvers with TypeScript, using classes and decorators!",
66
"keywords": [

website/i18n/en.json

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -811,6 +811,56 @@
811811
"version-2.0.0-rc.1/version-2.0.0-rc.1-validation": {
812812
"title": "Argument and Input validation",
813813
"sidebar_label": "Validation"
814+
},
815+
"version-2.0.0-rc.2/version-2.0.0-rc.2-authorization": {
816+
"title": "Authorization"
817+
},
818+
"version-2.0.0-rc.2/version-2.0.0-rc.2-azure-functions": {
819+
"title": "Azure Functions Integration"
820+
},
821+
"version-2.0.0-rc.2/version-2.0.0-rc.2-browser-usage": {
822+
"title": "Browser usage"
823+
},
824+
"version-2.0.0-rc.2/version-2.0.0-rc.2-complexity": {
825+
"title": "Query complexity"
826+
},
827+
"version-2.0.0-rc.2/version-2.0.0-rc.2-custom-decorators": {
828+
"title": "Custom decorators"
829+
},
830+
"version-2.0.0-rc.2/version-2.0.0-rc.2-dependency-injection": {
831+
"title": "Dependency injection"
832+
},
833+
"version-2.0.0-rc.2/version-2.0.0-rc.2-examples": {
834+
"title": "Examples",
835+
"sidebar_label": "List of examples"
836+
},
837+
"version-2.0.0-rc.2/version-2.0.0-rc.2-extensions": {
838+
"title": "Extensions"
839+
},
840+
"version-2.0.0-rc.2/version-2.0.0-rc.2-generic-types": {
841+
"title": "Generic Types"
842+
},
843+
"version-2.0.0-rc.2/version-2.0.0-rc.2-inheritance": {
844+
"title": "Inheritance"
845+
},
846+
"version-2.0.0-rc.2/version-2.0.0-rc.2-interfaces": {
847+
"title": "Interfaces"
848+
},
849+
"version-2.0.0-rc.2/version-2.0.0-rc.2-middlewares": {
850+
"title": "Middleware and guards"
851+
},
852+
"version-2.0.0-rc.2/version-2.0.0-rc.2-resolvers": {
853+
"title": "Resolvers"
854+
},
855+
"version-2.0.0-rc.2/version-2.0.0-rc.2-subscriptions": {
856+
"title": "Subscriptions"
857+
},
858+
"version-2.0.0-rc.2/version-2.0.0-rc.2-unions": {
859+
"title": "Unions"
860+
},
861+
"version-2.0.0-rc.2/version-2.0.0-rc.2-validation": {
862+
"title": "Argument and Input validation",
863+
"sidebar_label": "Validation"
814864
}
815865
},
816866
"links": {
Lines changed: 220 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,220 @@
1+
---
2+
title: Authorization
3+
id: version-2.0.0-rc.2-authorization
4+
original_id: authorization
5+
---
6+
7+
Authorization is a core feature used in almost all APIs. Sometimes we want to restrict data access or actions for a specific group of users.
8+
9+
In express.js (and other Node.js frameworks) we use middleware for this, like `passport.js` or the custom ones. However, in GraphQL's resolver architecture we don't have middleware so we have to imperatively call the auth checking function and manually pass context data to each resolver, which might be a bit tedious.
10+
11+
That's why authorization is a first-class feature in `TypeGraphQL`!
12+
13+
## Declaration
14+
15+
First, we need to use the `@Authorized` decorator as a guard on a field, query or mutation.
16+
Example object type field guards:
17+
18+
```ts
19+
@ObjectType()
20+
class MyObject {
21+
@Field()
22+
publicField: string;
23+
24+
@Authorized()
25+
@Field()
26+
authorizedField: string;
27+
28+
@Authorized("ADMIN")
29+
@Field()
30+
adminField: string;
31+
32+
@Authorized(["ADMIN", "MODERATOR"])
33+
@Field({ nullable: true })
34+
hiddenField?: string;
35+
}
36+
```
37+
38+
We can leave the `@Authorized` decorator brackets empty or we can specify the role/roles that the user needs to possess in order to get access to the field, query or mutation.
39+
By default the roles are of type `string` but they can easily be changed as the decorator is generic - `@Authorized<number>(1, 7, 22)`.
40+
41+
Thus, authorized users (regardless of their roles) can only read the `publicField` or the `authorizedField` from the `MyObject` object. They will receive `null` when accessing the `hiddenField` field and will receive an error (that will propagate through the whole query tree looking for a nullable field) for the `adminField` when they don't satisfy the role constraints.
42+
43+
Sample query and mutation guards:
44+
45+
```ts
46+
@Resolver()
47+
class MyResolver {
48+
@Query()
49+
publicQuery(): MyObject {
50+
return {
51+
publicField: "Some public data",
52+
authorizedField: "Data for logged users only",
53+
adminField: "Top secret info for admin",
54+
};
55+
}
56+
57+
@Authorized()
58+
@Query()
59+
authedQuery(): string {
60+
return "Authorized users only!";
61+
}
62+
63+
@Authorized("ADMIN", "MODERATOR")
64+
@Mutation()
65+
adminMutation(): string {
66+
return "You are an admin/moderator, you can safely drop the database ;)";
67+
}
68+
}
69+
```
70+
71+
Authorized users (regardless of their roles) will be able to read data from the `publicQuery` and the `authedQuery` queries, but will receive an error when trying to perform the `adminMutation` when their roles don't include `ADMIN` or `MODERATOR`.
72+
73+
However, declaring `@Authorized()` on all the resolver's class methods would be not only a tedious task but also an error-prone one, as it's easy to forget to put it on some newly added method, etc.
74+
Hence, TypeGraphQL support declaring `@Authorized()` or the resolver class level. This way you can declare it once per resolver's class but you can still overwrite the defaults and narrows the authorization rules:
75+
76+
```ts
77+
@Authorized()
78+
@Resolver()
79+
class MyResolver {
80+
// this will inherit the auth guard defined on the class level
81+
@Query()
82+
authedQuery(): string {
83+
return "Authorized users only!";
84+
}
85+
86+
// this one overwrites the resolver's one
87+
// and registers roles required for this mutation
88+
@Authorized("ADMIN", "MODERATOR")
89+
@Mutation()
90+
adminMutation(): string {
91+
return "You are an admin/moderator, you can safely drop the database ;)";
92+
}
93+
}
94+
```
95+
96+
## Runtime checks
97+
98+
Having all the metadata for authorization set, we need to create our auth checker function. Its implementation may depend on our business logic:
99+
100+
```ts
101+
export const customAuthChecker: AuthChecker<ContextType> = (
102+
{ root, args, context, info },
103+
roles,
104+
) => {
105+
// Read user from context
106+
// and check the user's permission against the `roles` argument
107+
// that comes from the '@Authorized' decorator, eg. ["ADMIN", "MODERATOR"]
108+
109+
return true; // or 'false' if access is denied
110+
};
111+
```
112+
113+
The second argument of the `AuthChecker` generic type is `RoleType` - used together with the `@Authorized` decorator generic type.
114+
115+
Auth checker can be also defined as a class - this way we can leverage the dependency injection mechanism:
116+
117+
```ts
118+
export class CustomAuthChecker implements AuthCheckerInterface<ContextType> {
119+
constructor(
120+
// Dependency injection
121+
private readonly userRepository: Repository<User>,
122+
) {}
123+
124+
check({ root, args, context, info }: ResolverData<ContextType>, roles: string[]) {
125+
const userId = getUserIdFromToken(context.token);
126+
// Use injected service
127+
const user = this.userRepository.getById(userId);
128+
129+
// Custom logic, e.g.:
130+
return user % 2 === 0;
131+
}
132+
}
133+
```
134+
135+
The last step is to register the function or class while building the schema:
136+
137+
```ts
138+
import { customAuthChecker } from "../auth/custom-auth-checker.ts";
139+
140+
const schema = await buildSchema({
141+
resolvers: [MyResolver],
142+
// Register the auth checking function
143+
// or defining it inline
144+
authChecker: customAuthChecker,
145+
});
146+
```
147+
148+
And it's done! 😉
149+
150+
If we need silent auth guards and don't want to return authorization errors to users, we can set the `authMode` property of the `buildSchema` config object to `"null"`:
151+
152+
```ts
153+
const schema = await buildSchema({
154+
resolvers: ["./**/*.resolver.ts"],
155+
authChecker: customAuthChecker,
156+
authMode: "null",
157+
});
158+
```
159+
160+
It will then return `null` instead of throwing an authorization error.
161+
162+
## Recipes
163+
164+
We can also use `TypeGraphQL` with JWT authentication.
165+
Here's an example using `@apollo/server`:
166+
167+
```ts
168+
import { ApolloServer } from "@apollo/server";
169+
import { expressMiddleware } from "@apollo/server/express4";
170+
import express from "express";
171+
import jwt from "express-jwt";
172+
import bodyParser from "body-parser";
173+
import { schema } from "./graphql/schema";
174+
import { User } from "./User.type";
175+
176+
// GraphQL path
177+
const GRAPHQL_PATH = "/graphql";
178+
179+
// GraphQL context
180+
type Context = {
181+
user?: User;
182+
};
183+
184+
// Express
185+
const app = express();
186+
187+
// Apollo server
188+
const server = new ApolloServer<Context>({ schema });
189+
await server.start();
190+
191+
// Mount a JWT or other authentication middleware that is run before the GraphQL execution
192+
app.use(
193+
GRAPHQL_PATH,
194+
jwt({
195+
secret: "TypeGraphQL",
196+
credentialsRequired: false,
197+
}),
198+
);
199+
200+
// Apply GraphQL server middleware
201+
app.use(
202+
GRAPHQL_PATH,
203+
bodyParser.json(),
204+
expressMiddleware(server, {
205+
// Build context
206+
// 'req.user' comes from 'express-jwt'
207+
context: async ({ req }) => ({ user: req.user }),
208+
}),
209+
);
210+
211+
// Start server
212+
await new Promise<void>(resolve => app.listen({ port: 4000 }, resolve));
213+
console.log(`GraphQL server ready at http://localhost:4000/${GRAPHQL_PATH}`);
214+
```
215+
216+
Then we can use standard, token based authorization in the HTTP header like in classic REST APIs and take advantage of the `TypeGraphQL` authorization mechanism.
217+
218+
## Example
219+
220+
See how this works in the [simple real life example](https://github.com/MichalLytek/type-graphql/tree/v2.0.0-rc.2/examples/authorization).

0 commit comments

Comments
 (0)