6th Practical Class:
BackEnd finalization!
Auth
Authentication vs Authorization
- Authentication asks who are you?
- Authorization asks whether you have access to the resource you want.
It is common to see combinations of both, you first need to authenticate in order to be authorized to use the resource.
JWT tokens
- Used for authentication on web by many of the authentication services
- Token is sent in request headers: , or using
- Holds a public information signed by server with a secret. Do not store private information
- Protected against tempering of the stored data
Example
Consists of 3 parts:
- , type and signing algorithm
- , data, called claims, defined by server, typically user data
- , signed encoded header and payload by server secret, used for verifying the token
You can read any JWT token data, but you can't change them! Try out here
Securing our application
Authentication providers
- Abstract the complexity of the authentication
- You don't store sensitive information
- Social logins
- Security!
- But, hard to change and costs money, still worth it usually.
- Auth0, Firebase Auth, AWS Cognito, etc.
Custom implementations
- Can be easy to implement, but probably not secure enough.
- Libraries for JWT handling available
- Our case, easy to show how to work with authentication/authorization
Example
On signUp/signIn, server creates a JWT token. (We're using library , all examples are included in the code).
Client has to include token for every request, usually in header, in GraphQL we can use :
Server verifies the token with the same secret used for creating the token.
In our case we authenticate the user in the GraphQL context.
Then we simply "authorize" user to use some of the resolvers.
Let's see the code
File upload
Unfortunately, GraphQL is not suitable for uploading files, CSRF vulnerability. You can read more here
Better solutions:
Signed URL uploads
- Uploads directly to storage
- Better work with files
- Complex, server needs to know about the upload
Dedicated file/image service
- Uploads to service, saves only URL/path
- Easier to implement
- Costs money
File upload using GraphQL
- using middleware
- requires server or other server implementation, where you can add middlewares
- Opens GraphQL server for simple requests without using request in order to use GraphQL multipart requests and upload files
- A custom Scalar needs to be added to the schema
- Apollo Server v4 has CSRF protection, client must send special headers:
Swap to express server
Detailed documentation for swapping to expressMiddleware
Defining and using the scalar.
(Be aware when using TS generators, you also have to adjust the generator to include custom Scalar types)
See the code for an implementation example for signUp mutation
Frontend
Form
- form value of type File