Skip to content

Commit e0e0b22

Browse files
committed
Add authentication
1 parent 8981f7c commit e0e0b22

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

src/index.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { ApolloServer, gql } from 'apollo-server'
2+
import { getAuthIdFromJWT } from './util/auth'
23

34
const reviews = [
45
{
@@ -10,9 +11,14 @@ const reviews = [
1011
const server = new ApolloServer({
1112
typeDefs: gql`
1213
type Query {
14+
me: User
1315
hello: String!
1416
reviews: [Review!]!
1517
}
18+
type User {
19+
firstName: String
20+
lastName: String
21+
}
1622
type Review {
1723
text: String!
1824
stars: Int
@@ -28,6 +34,7 @@ const server = new ApolloServer({
2834
`,
2935
resolvers: {
3036
Query: {
37+
me: (_, __, context) => context.user,
3138
hello: () => '🌍🌏🌎',
3239
reviews: () => reviews
3340
},
@@ -43,6 +50,20 @@ const server = new ApolloServer({
4350
return review
4451
}
4552
}
53+
},
54+
context: async ({ req }) => {
55+
const context = {}
56+
57+
const jwt = req.headers.authorization
58+
const authId = await getAuthIdFromJWT(jwt)
59+
if (authId === 'github|1615') {
60+
context.user = {
61+
firstName: 'John',
62+
lastName: 'Resig'
63+
}
64+
}
65+
66+
return context
4667
}
4768
})
4869

src/util/auth.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import jwt from 'jsonwebtoken'
2+
import jwks from 'jwks-rsa'
3+
import { promisify } from 'util'
4+
5+
const verify = promisify(jwt.verify)
6+
7+
const jwksClient = jwks({
8+
cache: true,
9+
rateLimit: true,
10+
jwksUri: 'https://graphql.auth0.com/.well-known/jwks.json'
11+
})
12+
13+
const getPublicKey = (header, callback) => {
14+
jwksClient.getSigningKey(header.kid, (e, key) => {
15+
callback(e, key.publicKey || key.rsaPublicKey)
16+
})
17+
}
18+
19+
export const getAuthIdFromJWT = async token => {
20+
if (!token) {
21+
return
22+
}
23+
24+
const verifiedToken = await verify(token, getPublicKey, {
25+
algorithms: ['RS256'],
26+
audience: 'https://api.graphql.guide',
27+
issuer: 'https://graphql.auth0.com/'
28+
})
29+
30+
return verifiedToken.sub
31+
}

0 commit comments

Comments
 (0)