Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Axios formatting and Rails controller validation? #1380

Closed
GunnarPDX opened this issue Jan 30, 2020 · 1 comment
Closed

Axios formatting and Rails controller validation? #1380

GunnarPDX opened this issue Jan 30, 2020 · 1 comment

Comments

@GunnarPDX
Copy link

Describe the issue
What is the proper formatting for Axios headers and authentication within rails controllers? My app seems to be handling authentication properly on the backed, at least log in and registrations but further requests fail to authenticate for user_signed_in?. I think the issue is with my Axios requests but not positive as I am very new to this. Could someone take a quick look at the code below and tell me if I'm doing this correctly, I looked all over for examples and could not find and specific to this gem w/react so I'm not positive if I am passing the token correctly.

Example Code
Axios Post (Login):

axios.post('/api/v1/auth/sign_in', {email: this.state.email, password: this.state.password})
            .then((res) => {
                const {token} = res.headers;   // Should the token include the whole header?
                console.log(res.headers);
                localStorage.setItem('token', token);
            })
            .catch(function(err) {
                console.log(err);
            });

Response Header:

{access-control-allow-methods: "GET, POST, OPTIONS, DELETE, PUT", access-control-allow-origin: "*", access-control-expose-headers: "access-token, expiry, token-type, uid, client", access-control-max-age: "7200", access-token: "XL2KRnNgTojeMEinm3K0sw", …}

access-control-allow-methods: "GET, POST, OPTIONS, DELETE, PUT"
access-control-allow-origin: "*"
access-control-expose-headers: "access-token, expiry, token-type, uid, client"
access-control-max-age: "7200"
access-token: "XL2KRnNeTojeMEizm3K2sw"
cache-control: "max-age=0, private, must-revalidate"
client: "JGr_EaURKU4DDliyLp8_fg"
connection: "close"
content-encoding: "gzip"
content-type: "application/json; charset=utf-8"
date: "Thu, 30 Jan 2020 20:57:33 GMT"
etag: "W/"016aa9a0071584fe6bcc72577c6f783d""
expiry: "1581627454"
token-type: "Bearer"
transfer-encoding: "chunked"
uid: "[email protected]"
vary: "Origin, Accept-Encoding"
x-powered-by: "Express"
x-request-id: "9d2f9dcc-d567-4269-8557-5x3dqwcb23e2"
x-runtime: "0.196702"

Axios Get (Testing the api):

const token = localStorage.getItem('token');
        if(token !== null){
            axios.get('http://localhost:3001/api/v1/demo', {
                headers: {'Authorization': 'Bearer ' + token}
            })
                .then((res) => {
                    console.log(res);
                    this.setState({message: res.data.message});
                })
                .catch(function(err) {
                    console.log(err);
                });
        }

Rails Controller for demo:

class DemoController < ApplicationController

    def index
      if user_signed_in?
        render json: {success: true, message: 'hello from backend (signed in)'}, status: 200
      else
        render json: {success: true, message: 'hello from backend (signed out)'}, status: 200
      end
    end

  end

Logs

13:21:17 api.1  | Started POST "/api/v1/auth/sign_in" for 127.0.0.1 at 2020-01-30 13:21:17 -0800
13:21:17 api.1  | Processing by DeviseTokenAuth::SessionsController#create as HTML
13:21:17 api.1  |   Parameters: {"email"=>"[email protected]", "password"=>"[FILTERED]", "session"=>{"email"=>"[email protected]", "password"=>"[FILTERED]"}}
13:21:17 api.1  | Unpermitted parameter: :session
13:21:17 api.1  | Unpermitted parameter: :session
13:21:17 api.1  |   User Load (0.7ms)  SELECT  "users".* FROM "users" WHERE "users"."email" = $1 AND "users"."provider" = $2 LIMIT $3  [["email", "[email protected]"], ["provider", "email"], ["LIMIT", 1]]
13:21:17 api.1  |   ↳ /Users/gunnarrosenberg/.rvm/gems/ruby-2.7.0/gems/activerecord-5.2.4.1/lib/active_record/log_subscriber.rb:98
13:21:17 api.1  | Unpermitted parameter: :session
13:21:17 api.1  | Unpermitted parameter: :session
13:21:18 api.1  | /Users/gunnarrosenberg/.rvm/gems/ruby-2.7.0/gems/activerecord-5.2.4.1/lib/active_record/transactions.rb:212: warning: Using the last argument as keyword parameters is deprecated; maybe ** should be added to the call
13:21:18 api.1  | /Users/gunnarrosenberg/.rvm/gems/ruby-2.7.0/gems/activerecord-5.2.4.1/lib/active_record/connection_adapters/abstract/database_statements.rb:260: warning: The called method `transaction' is defined here
13:21:18 api.1  | /Users/gunnarrosenberg/.rvm/gems/ruby-2.7.0/gems/activerecord-5.2.4.1/lib/active_record/connection_adapters/abstract/transaction.rb:171: warning: Using the last argument as keyword parameters is deprecated; maybe ** should be added to the call
13:21:18 api.1  | /Users/gunnarrosenberg/.rvm/gems/ruby-2.7.0/gems/activerecord-5.2.4.1/lib/active_record/connection_adapters/abstract/transaction.rb:97: warning: The called method `initialize' is defined here
13:21:18 api.1  |    (0.1ms)  BEGIN
13:21:18 api.1  |   ↳ /Users/gunnarrosenberg/.rvm/gems/ruby-2.7.0/gems/activerecord-5.2.4.1/lib/active_record/log_subscriber.rb:98
13:21:18 api.1  | /Users/gunnarrosenberg/.rvm/gems/ruby-2.7.0/gems/activerecord-5.2.4.1/lib/active_record/persistence.rb:705: warning: Using the last argument as keyword parameters is deprecated; maybe ** should be added to the call
13:21:18 api.1  | /Users/gunnarrosenberg/.rvm/gems/ruby-2.7.0/gems/activerecord-5.2.4.1/lib/active_record/timestamp.rb:105: warning: The called method `_update_record' is defined here
13:21:18 api.1  |   User Update (0.5ms)  UPDATE "users" SET "tokens" = $1, "updated_at" = $2 WHERE "users"."id" = $3  [["tokens", "\"{\\\"zLo75MYQX-qKN5-jMsUncw\\\":{\\\"token\\\":\\\"$2a$10$jiecfTuvjjcKShxVPVjJmeqX08G2JdxeWj/5CjfA0zS1aw6VbA0Ma\\\",\\\"expiry\\\":1581575104,\\\"last_token\\\":\\\"$2a$10$HiGtOVbBrkCvRX/14x0.XeYaNBhxQdfqv5JItm0XGrnbGqKqE5a.2\\\",\\\"updated_at\\\":\\\"2020-01-30 06:25:04 UTC\\\"},\\\"zR4gfB2EPkv84hQBGutXxA\\\":{\\\"token\\\":\\\"$2a$10$HbgdN8FyWkrIpzl/CP4B6ub5O/SApbejtasPjE6x9tlUjB3JIonRa\\\",\\\"expiry\\\":1581576561,\\\"last_token\\\":\\\"$2a$10$KA2Vk2pBzsDHiSSpfjPAy.W7t2E8pM1t1K6rw8LxBlmf4vKQ1dkBO\\\",\\\"updated_at\\\":\\\"2020-01-30 06:49:21 UTC\\\"},\\\"1mfN8qy5aPi8pm90ML0bNg\\\":{\\\"token\\\":\\\"$2a$10$gCL5pJKVrB74FpVPiLDug.9nkZUhAqmtlK2fiLfTf6FizqUeRRhWC\\\",\\\"expiry\\\":1581580357,\\\"last_token\\\":\\\"$2a$10$4/IyYJOiwZktI9qs8XjXH.oMzXf7QapsVSO0fmOUvtGDynm9az0Oy\\\",\\\"updated_at\\\":\\\"2020-01-30 07:52:37 UTC\\\"},\\\"7RSvvzJfxmShUwxySx99XA\\\":{\\\"token\\\":\\\"$2a$10$q9MnXvmw1XGTLcC.YT2cb.rcu2FvMJADQIkm7vPz34/9Jc4rFr7DO\\\",\\\"expiry\\\":1581582584,\\\"last_token\\\":\\\"$2a$10$BXiz17UJzRYaycBU4rOwJO/He9./2Op25QeKbBwuoekkMvbnibH6O\\\",\\\"updated_at\\\":\\\"2020-01-30 08:29:44 UTC\\\"},\\\"yi8e4ojG9zc5Hbg2EWR4NA\\\":{\\\"token\\\":\\\"$2a$10$.jT37LGaStJB8nTvlco7zuNhC9sNQk9m0UQhlDi/Y/M6.DaGk3xHe\\\",\\\"expiry\\\":1581625010,\\\"last_token\\\":\\\"$2a$10$MT33h95dKegora4dFMa71ODXozvgfeWa6uboXG/YLDde9BcjkXb2C\\\",\\\"updated_at\\\":\\\"2020-01-30 20:16:50 UTC\\\"},\\\"eLD9Uo3vdWaytX_kWQEX1Q\\\":{\\\"token\\\":\\\"$2a$10$FF7XS8jCvqX..bXZ.OKhM.GlL4K2DcuexHdXQx0zwQZlxmIUxffmG\\\",\\\"expiry\\\":1581625301,\\\"last_token\\\":\\\"$2a$10$3i6d0jNVxjHN7b3DvVO5weMuTDQ7lQj2w6SsYknD.8uyD/IkUkfAS\\\",\\\"updated_at\\\":\\\"2020-01-30 20:21:41 UTC\\\"},\\\"Rvc2cGkNPGXUnPhcQe-zag\\\":{\\\"token\\\":\\\"$2a$10$8V4mj1n1gp0WQQdeOYL7sOcq/cGc8Q7K7fyeAsu8.p5mwNUSd0Qd6\\\",\\\"expiry\\\":1581627425,\\\"last_token\\\":\\\"$2a$10$6IM9X9O3dVU1uj7Jk.Y3BeRQ9HNLjPB3m6Lqjy61XFQYQIj7tqVU6\\\",\\\"updated_at\\\":\\\"2020-01-30 20:57:05 UTC\\\"},\\\"JGr_EeURWU4DDliuLp8_fg\\\":{\\\"token\\\":\\\"$2a$10$fTZQVTAyPx8C83WIZq3paeBgKeurRjLctAWYL3nNYfi5M4V4z4WAq\\\",\\\"expiry\\\":1581627453,\\\"last_token\\\":\\\"$2a$10$1pqWnrpY3h/6Jzoh1CjhkelhG7C.GuOgySdi6LPtN6lnOt5OBfc4q\\\",\\\"updated_at\\\":\\\"2020-01-30 20:57:33 UTC\\\"},\\\"XtA839tKeDMLacWQPl1w9w\\\":{\\\"token\\\":\\\"$2a$10$QSErx5AtlZ5RqhD6bV/bIeO49CyT0BPwoUdSQ1Bg1eERLWD7d34.i\\\",\\\"expiry\\\":1581628728,\\\"last_token\\\":\\\"$2a$10$wLp6XryOPZtA6R2gZ1Ddo.rSFZIp2jlE2V/DxHTQht/4DN/bG621K\\\",\\\"updated_at\\\":\\\"2020-01-30 21:18:48 UTC\\\"},\\\"6kuweZLd8aKYCtyWh00A8g\\\":{\\\"token\\\":\\\"$2a$10$y7x.DqI3shetqDZQDulz8OFXbli.Nsdf/jXNJtay6E3p4XkPLWSYG\\\",\\\"expiry\\\":1581628878}}\""], ["updated_at", "2020-01-30 21:21:18.053476"], ["id", 28]]
13:21:18 api.1  |   ↳ /Users/gunnarrosenberg/.rvm/gems/ruby-2.7.0/gems/activerecord-5.2.4.1/lib/active_record/log_subscriber.rb:98
13:21:18 api.1  |    (2.2ms)  COMMIT
13:21:18 api.1  |   ↳ /Users/gunnarrosenberg/.rvm/gems/ruby-2.7.0/gems/activerecord-5.2.4.1/lib/active_record/log_subscriber.rb:98
13:21:18 api.1  |    (0.1ms)  BEGIN
13:21:18 api.1  |   ↳ /Users/gunnarrosenberg/.rvm/gems/ruby-2.7.0/gems/activerecord-5.2.4.1/lib/active_record/log_subscriber.rb:98
13:21:18 api.1  |   User Update (0.3ms)  UPDATE "users" SET "updated_at" = $1, "sign_in_count" = $2, "current_sign_in_at" = $3, "last_sign_in_at" = $4 WHERE "users"."id" = $5  [["updated_at", "2020-01-30 21:21:18.059613"], ["sign_in_count", 14], ["current_sign_in_at", "2020-01-30 21:21:18.058355"], ["last_sign_in_at", "2020-01-30 21:18:48.635417"], ["id", 28]]
13:21:18 api.1  |   ↳ /Users/gunnarrosenberg/.rvm/gems/ruby-2.7.0/gems/activerecord-5.2.4.1/lib/active_record/log_subscriber.rb:98
13:21:18 api.1  |    (0.3ms)  COMMIT
13:21:18 api.1  |   ↳ /Users/gunnarrosenberg/.rvm/gems/ruby-2.7.0/gems/activerecord-5.2.4.1/lib/active_record/log_subscriber.rb:98
13:21:18 api.1  |   User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 28], ["LIMIT", 1]]
13:21:18 api.1  |   ↳ /Users/gunnarrosenberg/.rvm/gems/ruby-2.7.0/gems/activerecord-5.2.4.1/lib/active_record/log_subscriber.rb:98
13:21:18 api.1  | Completed 200 OK in 188ms (Views: 0.1ms | ActiveRecord: 8.7ms)
13:21:18 api.1  | 
13:21:18 api.1  | 

13:19:41 api.1  | Started GET "/api/v1/demo" for ::1 at 2020-01-30 13:19:41 -0800
13:19:41 api.1  | /Users/gunnarrosenberg/.rvm/gems/ruby-2.7.0/gems/activemodel-5.2.4.1/lib/active_model/type/integer.rb:13: warning: Using the last argument as keyword parameters is deprecated; maybe ** should be added to the call
13:19:41 api.1  | /Users/gunnarrosenberg/.rvm/gems/ruby-2.7.0/gems/activemodel-5.2.4.1/lib/active_model/type/value.rb:8: warning: The called method `initialize' is defined here
13:19:41 api.1  | /Users/gunnarrosenberg/.rvm/gems/ruby-2.7.0/gems/activerecord-5.2.4.1/lib/active_record/connection_adapters/postgresql/oid/specialized_string.rb:12: warning: Using the last argument as keyword parameters is deprecated; maybe ** should be added to the call
13:19:41 api.1  | /Users/gunnarrosenberg/.rvm/gems/ruby-2.7.0/gems/activemodel-5.2.4.1/lib/active_model/type/value.rb:8: warning: The called method `initialize' is defined here
13:19:41 api.1  |    (0.4ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
13:19:41 api.1  |   ↳ /Users/gunnarrosenberg/.rvm/gems/ruby-2.7.0/gems/activerecord-5.2.4.1/lib/active_record/log_subscriber.rb:98
13:19:41 api.1  | Processing by Api::V1::DemoController#index as HTML
13:19:41 api.1  | Completed 200 OK in 1ms (Views: 0.2ms | ActiveRecord: 0.0ms)

Expected behavior

I should be getting message: 'hello from backend (signed in)' when signed in

I instead receive message: 'hello from backend (signed out)' (see controller example above)

Environment:

  • Ruby: [2.7.0]
  • Rails: [5.2.4]
  • Postgres: pg [1.2.2]
  • devise_token_auth [1.1.3]
  • Axios Version [0.19.2]
  • OS: [macOS Catalina 10.15.2]
  • Browser [Chrome]
  • Browser Version [79]
  • React: [16.12.0] (create-react-app)

Config

in: config/initializers/devise_token_auth.rb
config.change_headers_on_each_request = false

@GunnarPDX
Copy link
Author

Got it to work by formatting my headers like this

            axios.post('/api/v1/auth/sign_in', {email: this.state.email, password: this.state.password})
            .then((res) => {
                window.localStorage.setItem('access-token', res.headers['access-token']);
                window.localStorage.setItem('client', res.headers['client']);
                window.localStorage.setItem('uid', res.headers['uid']);
            })
            .catch(function(err) {
                console.log(err);
            });

and

        const token = localStorage.getItem('access-token');
        const client = localStorage.getItem('client');
        const uid = localStorage.getItem('uid');
        axios.get('http://localhost:3001/api/v1/demo', {
            headers: {'Content-Type': 'application/json', 'access-token' : token, 'client':client, 'uid': uid}
        })
            .then((res) => {
                console.log(res);
                this.setState({message: res.data.message});
            })
            .catch(function(err) {
                console.log(err);
            });

Hopefully, this will help someone else

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant