Guide: Authentication
Ok you're doing great! At this point your database should be set up. But it doesn"t do much on it's own right? So let's add some authentication to our app!
Strafer uses Auth.js for authentication. It supports many authentication providers like Google, Facebook, Twitter, GitHub, etc. By default Strafer supports Magic links and Google OAuth.
The config file for Auth.js is located at @/core/auth.ts
Make sure you have the following environment variables set up in your
.env.local
file:
NEXTAUTH_SECRET
is a random string used by the Auth.js to encrypt tokens and
email verification hashes. It's mandatory to keep things secure.
With Google Oauth
Let's start by adding Google OAuth to our app. See Google Provider for reference.
- Start by creating a new project in the Google Developer Console.
- Then go to APIs & Services then Oauth consent screen. Select external User type then create.
- Fill in the required fields and save.
- On the Scopes section, add
./auth/userinfo.email
and./auth/userinfo.profile
scopes. - Under Test users, add your email address that you will use during development.
- Go to Credentials then Create Credentials then OAuth client ID.
- Select
Web Application
as the Application type. - Add
http://localhost:3000
andhttps://domain.com
to Authorized JavaScript origins. - Add
http://localhost:3000/api/auth/callback/google
andhttps://domain.com/api/auth/callback/google
to Authorized redirect URIs. - Copy Client ID and Client Secret and add them to your .env.local file.
- And voila! You're done.
Now you should be able to login with Google.
Head over to http://localhost:3000/auth/signin
to test it out.
You should be redirected to http://localhost:3000/protected
after logging in.
A new user should be created in your database.
Don't forget to publish your app under OAuth consent screen once it's ready for production! It can take a few days for approval. So make sure to plan ahead.