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 .envYou need to configure these credentials from a new Github OAuth2 app as environment variables:
GITHUB_CLIENT_IDGITHUB_CLIENT_SECRET
- Go to github.com and navigate to your profile. Click on your profile icon in the upper right corner and enter
Settings. - In the lower left side find Developer Settings and navigate to OAuth Apps.
- Click
New OAuth Appand give your app a nice name. For the purposes of the example, it is best to set the Homepage URL tohttp://localhost:8000and Authorization callback URL tohttp://localhost:8000/login. (Application description is optional). - Register the application.
- Copy Client ID and Client Secret to the .env file.
- Replace
__CLIENT_ID__inlogin.html - Serve
login.html, for example by usingpython -m SimpleHTTPServer - Open
https://localhost:8000/login.htmlin a browser, open the DevTools and authenticate with your Github account - Copy the code printed in the Console of your DevTools
In order to obtain Github code you can also use this little hack.
- Navigate to
https://github.com/login/oauth/authorize?client_id={GITHUB_CLIENT_ID}&scope=userand replace{GITHUB_CLIENT_ID}with your Github client ID. - Authorise access to the account and you will be redirected to
localhost:8000/login.html?code={GITHUB_CODE}. - Copy the
{GITHUB_CODE}part oflocalhost:8000/login.html?code={GITHUB_CODE}url to your GraphQL playground where you can test authentication.
- To authenticate the user use
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.
- To get info about currently authenticated user use
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.
- To create a Note use
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
}
}
}- To read, delete or update Note you will have to be authenticated, otherwise NotAuthorized Error will be returned.
query MyNote($id: ID!) {
note(id: $id) { text }
}yarn install
yarn start
# Open http://localhost:5000/MIT