This post is an update on the weather_api_app we built earlier. Our goal for this blog is to create an authentication for the back-end API using Devise Gem.
I'm assuming that the front-end and back-end of the application will be hosted on different servers, so we will use rack-cors
to help us accept requests from different origins.
Add this to your Gemfile:
Run bundle install
and add an initializer on config/initializers/cors.rb
The next step is to add devise
, devise-jwt
and jsonapi-serializer
gem:
Setup Devise
Do the typical devise installation and create a devise User model then do the following modifications.
Before running the devise migration, you can add the following lines:
We will be using this for the revocation strategy. Next is to add the strategy to the user model and configure it to use the correct revocation strategy:
Setup devise-jwt
Set up a secret we will be using for JWT. On the terminal do this:
Save the key on an ENV variable. In my case, I'm saving the variable as DEVISE_JWT_SECRET_KEY
.
Update config/initializers/devise.rb:
Setup jsonapi_serializer
Generate the serializer that we will be using later when we update the devise controllers so we return a json:
Update Devise controllers
Update the Registration controller to respond to JSON requests
Update the Session controller to respond to JSON requests
If you try out the API you will encounter this error:
ActionDispatch::Request::Session::DisabledSessionError (Your application has sessions disabled. To write to the session you must first configure a session store):
This is because the Rails application session store is not configured properly.
You can configure it by add a `config/initiliazers/session_store.rb` file. Then add this line:
On the `config/application.rb`, add the following lines:
Testing with Postman
User Registration
User Login
Accessing weather endpoint with logged-in user
User logout and accessing weather endpoint
Hello there!
Do you have a startup idea or an exciting project you’re passionate about? I’d love to bring your vision to life!
I’m a software developer with 13 years of experience in building apps for startups, I specialize in Rails + Hotwire/React.
Whether you’re looking to innovate, grow your business, or bring a creative idea to the forefront, I’m here to provide tailored solutions that meet your unique needs.
Let’s collaborate to make something amazing!
Sincerely,
Ademar Tutor
hey@ademartutor.com