GraphQL Server examples: Authentication
This example shows how to implement Github Authentication with GraphQL Server,
using graphql-yoga
and other tools.
prisma deploy # copy simple API endpoint into the `PRISMA_ENPOINT` env var in .env
You need to configure these credentials from a new Github OAuth2 app as environment variables:
GITHUB_CLIENT_ID
GITHUB_CLIENT_SECRET
Settings
.New OAuth App
and give your app a nice name. For the purposes of the example, it is best to set the Homepage URL to http://localhost:8000
and Authorization callback URL to http://localhost:8000/login
. (Application description is optional).__CLIENT_ID__
in login.html
login.html
, for example by using python -m SimpleHTTPServer
https://localhost:8000/login.html
in a browser, open the DevTools and authenticate with your Github accountIn order to obtain Github code
you can also use this little hack.
https://github.com/login/oauth/authorize?client_id={GITHUB_CLIENT_ID}&scope=user
and replace {GITHUB_CLIENT_ID}
with your Github client ID.localhost:8000/login.html?code={GITHUB_CODE}
.{GITHUB_CODE}
part of localhost:8000/login.html?code={GITHUB_CODE}
url to your GraphQL playground where you can test authentication.Mutation authenticate
:mutation LoginOrSignup {
authenticate(githubCode: "mygithubcode") {
token
user {
name
notes
}
}
}
Every time authenticate
is called user info is loaded from Github server using provided code. If code is valid, user id is compared against existing users. If no user with such id exists, new one is created, otherwise the existsing one is returned.
Query me
:query Me {
me {
name
bio
public_repos
notes {
id
text
}
}
}
Server will use the token, provided under Authorization: Bearer <token>
http header, to identify userId and will search the database for an existsing user.
Mutation createNote
, this will create a note connected with your profile.mutation NewNote {
createNote(text: "Super cool text.") {
id
text
}
}
query MyProfile {
me {
id
notes { # <- Note will appear here
id
text
}
}
}
query MyNote($id: ID!) {
note(id: $id) { text }
}
yarn install
yarn start
# Open http://localhost:5000/
MIT