简体   繁体   中英

Rails returning 401 Unauthorised for User Auth Flow - Rails, devise gem, Devise_token_auth gem

Giving my first go at linking my React Native front end to my rails API back end. To do this I'm working with a user authentication flow and more specifically, signing in (creating the user on the database via User.create and a User model).

I've set up the Front end to work with Redux and send a fetch request, posting data from a form as JSON to rails. The data goes to Rails without any problem.

However, the problem seems to be coming from Rails, where I'm getting a 401 in the console 401 Unauthorized with the param going through Parameters: {"session"=>{}} . Why is this the case and how can I fix it? I've tried a bunch of solutions on SO, GitHub and some independent forms and nothing is working.

Essentially the action I want is for React to send the user data submitted in the username and password (seems all good there so far), Rails to process the username and password in the overridden sessions controller (it seems to be doing that) and to return a 'success' status and user authentication token which we can store in react native.

The SignInAction.js from React Native

export const emailChanged = (email) => {
  return {
    type: 'EMAIL_CHANGED',
    payload: email
  };
};

export const passwordChanged = (password) => {
  return {
    type: 'PASSWORD_CHANGED',
    payload: password
  };
};

export const loginUser = ({ email, password }) => {
  return (dispatch) => {
    dispatch({
      type: 'LOAD_SPINNER'
    });
    fetch('http://localhost:3000/api/v1/auth/sign_in/', {
        method: 'POST',
        headers: {
            //headers beyond log in user should contain the user authentication token to prove authentication
          Accept: 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          // user: {
            email,
            password,
          // }
        })
      }).then((response) => {
        console.log(response);
        //this line is a problem
        if (response.status === 401) {
          console.log('AUTHENTICATION ERROR!!');
          dispatch({
            type: 'LOGIN_FAILED'
          });
        } else {
          console.log('SUCCESS!!');
          response.json().then(data => {
            console.log(data);
            dispatch({
              type: 'LOGIN_USER_SUCCESS',
              payload: data
            });
          });
        }
      });
  };
};

The Routes.rb from Rails

Rails.application.routes.draw do


  namespace :api do
   scope :v1 do
    mount_devise_token_auth_for 'User', at: 'auth', controllers: {
        registrations: 'api/v1/overrides/registrations',
        sessions: 'api/v1/overrides/sessions'
        }
    end
  end
end

The /api/v1/overrides/sessions_controller.rb from Rails

module Api::V1::Overrides
 class SessionsController < DeviseTokenAuth::SessionsController
     # Prevent session parameter from being passed
        # Unpermitted parameter: session
        wrap_parameters format: []
 end
end

Had the same problem, could never make it work with fetch, I assume there is some wrong header being sent impossible to track.

I switch to axios ( yarn add axios ) and then:

axios.post("http://localhost:3000/users/sign_in", {
      user: {
        email: "1@test.com",
        password: "123123",
      },
});

Problem solved

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM