2
votes

Can anyone point out a good resource on how to implement authentication/authorization using Rails API with React?

I've been spending a week or two trying to figure out how to combine the two and I haven't been able to, it's driving me insane.

There are people who says HTTP cookie only authentication is better whereas some people say token authentications are better. Then comes authorization. Then connecting. There's so much going on at once I can't decipher what method is the best practice.

Right now I am trying to use devise and pundit for authenticating and authorizing users, but then there are gems like simple-token-authentication, Knock, etc..

Please help me out.

Thank you.

2

2 Answers

0
votes

for rails server part you can use bcrypt / devise to authenticate user if it's correct and then using JsonWebToken to generate token and returned it to user and here is sample to encode using JsonWebToken

Gemfile

gem 'devise'
gem 'jwt', '~> 2.2'

controller/api/tokens_Controller.rb

class TokensController < ApplicationController
  def create
    @user = User.find_by_email(user_params[:email])
    if @user && @user.valid_password?(user_params[:password])
      render json: {
        token: JsonWebToken.encode(user_id: @user.id),
        email: @user.email
      }
    else
      head :unauthorized
    end
  end

  private

  def user_params
    params.require(:user).permit(:email, :password)
  end
end

and here is good book to read if you want to learn more, API on rails 6 by Alexandre,

on React part you can use Axios and if user success authenticated then received token, you can set token to be valid as long as you like (1 day, 1 week, 2 months etc), each time user request page / data that need authentication, user must send the token (you can put inside http header) here is sample from react part

import axios from 'axios';

export default axios.create({
  baseURL: 'http://your_api_server/api',
  headers: {
    Authorization: {put your token here}
  }
})
0
votes

So after messing around with axios and JWT, I now have a functional login/sign up page!

https://medium.com/@taiseiyamadashindosu/2020-authenticating-and-authorizing-your-react-app-with-rails-api-1-2-5f7f23380e1a

I wrote a medium article on how to get with this.