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

Getting 401 when trying to access resource that requires auth #7

Open
mclark4386 opened this issue Apr 19, 2015 · 16 comments
Open

Getting 401 when trying to access resource that requires auth #7

mclark4386 opened this issue Apr 19, 2015 · 16 comments

Comments

@mclark4386
Copy link

Hello,
I'm using devise_token_auth and j-toker for authentication. To be fair this is my first time using it, but also to be fair I think I've read all of the important parts of the Readme. That said I have get it to signup and sign in/out, but can't seem to get $.getJSON to work with it. I'm not doing any custom ajax setup. Any help would be great!

To clarify, the way I am trying to make this work, as this is how I understand it to work, is to sign-in and then simply make the $.getJSON request on a button press after that. This gives me the following console message on the rails server: Filter chain halted as :authenticate_user! rendered or redirected
And then a 401 on the client side. I have verified that this all works perfectly manually, so it's something with the way I'm using j-toker.

Sorry if this is just me being stupid, but there isn't a lot out there about j-toker and I read everything in the readme that seemed applicable.

Thanks!

@enricribas
Copy link

I'm seeing the same issue. When I "binding.pry" in the authenticate_user! method of my controller. I don't get a header called "access-token"

token = request.headers['access-token'] => nil  # 

However,

cookies["authHeader"] => {"access-token": ... etc. }

I'm using jquery $.ajax which j-toker expects and sets the request headers in the beforeSend according to docs. Yet, inspecting the browser network tab does not show the Headers.

    $.ajaxSetup({
      beforeSend: function(xhr, settings) {
        // append outbound auth headers
        $.auth.appendAuthHeaders(xhr, settings);
      }
    });

Adding this manually to jQuery, however, works.

I was under the impression that this happened automatically?

@andreasseiler
Copy link

Same here unfortunately ... can't get it fixed with your suggestion. How exactly did you fix the issue @enricribas ?

@lynndylanhurley
Copy link
Owner

Hi, are you guys using the module with CommonJS or AMD? (using import or require)?

@andreasseiler
Copy link

neither, just via the script tag. First jquery, deparam, cookies, pubsub then j-toker. should work right?

@lynndylanhurley
Copy link
Owner

It should work out of the box. Before the request was made, was the authHeaders cookie / localStorage value set?

And also, is there anything else in your codebase that sets the beforeSend callback? It's possible that it may have been overwritten by something else.

@andreasseiler
Copy link

No, neither of the values has been set ...

@lynndylanhurley
Copy link
Owner

That means the user hasn't been authenticated, or the authentication was unsuccessful for some reason.

When you sign in, is the authHeaders value set afterward?

@andreasseiler
Copy link

No it is not, seems like the getResponseHeader method does not "know" the keys "access-token" etc... just tried to debug your code but not sure yet why there is no return value ...

@andreasseiler
Copy link

It should work correctly if getResponseHeader or getAllResponseHeaders would return the token information. In the console I see the headers displayed correctly, but the functions only return Content-Type and Cache-Control.

Maybe you have any idea what the reason for that could be?

@lynndylanhurley
Copy link
Owner

Are the headers returned by the server on a successful login?

@andreasseiler
Copy link

Yes, the header contains all valid info
Am 20.08.2015 21:30 schrieb "Lynn Dylan Hurley" notifications@github.com:

Are the headers returned by the server on a successful login?


Reply to this email directly or view it on GitHub
#7 (comment)
.

@lynndylanhurley
Copy link
Owner

Can you post your configuration block?

@andreasseiler
Copy link

$.auth.configure({
apiUrl: 'http://localhost:3000/api'
});

You mean this?

@woniesong92
Copy link

@lynndylanhurley I also have the same problem. It seems that after a successful Auth.emailSignIn the subsequent calls don't have the appropriate headers and get returned 401.

$(function() {
  Auth.configure({
    apiUrl: 'http://localhost:3000/api'
  });

  Auth.emailSignIn({
    email: 'd@gmail.com',
    password: '12341234',
  }).then(function(user) {
    console.log(user)

    $.ajax ({
      url: "http://localhost:3000/api/playlists",
      type: "POST",
      data: JSON.stringify({"playlist": {name: 'jjambbong'}}),
      dataType: "json",
      contentType: "application/json",
      success: function(data){
        console.log(data);
        //401
      }
    });
  })

  // this block doesnt work either
  // $.post("http://localhost:3000/api/playlists", {
  //   name: 'jjambbong'
  // }, function(data) {
  //   console.log("playlist created");
  // })

@lynndylanhurley Here are the response headers

Access-Control-Allow-Credentials:true
Access-Control-Allow-Methods:GET, POST, OPTIONS, DELETE, PUT
Access-Control-Allow-Origin:http://localhost:8080
Access-Control-Expose-Headers:access-token, expiry, token-type, uid, client
Access-Control-Max-Age:1728000
Access-Token:HyJuT1ZmRcJNsec0K-_AQg
Cache-Control:max-age=0, private, must-revalidate
Client:BrxMp2cDxKsTk13ToMOEow
Connection:Keep-Alive
Content-Length:129
Content-Type:application/json; charset=utf-8
Date:Tue, 22 Mar 2016 11:10:56 GMT
Etag:W/"5cf6338878de2ecf13b6da5461fd863d"
Expiry:1459854656
Server:WEBrick/1.3.1 (Ruby/2.3.0/2015-12-25)
Token-Type:Bearer
Uid:d@gmail.com
Vary:Origin
X-Content-Type-Options:nosniff
X-Frame-Options:SAMEORIGIN
X-Request-Id:afc4950b-fbe6-4d54-93a6-d41633e3cb35
X-Runtime:0.215913
X-Xss-Protection:1; mode=block

@kunovsky
Copy link

kunovsky commented Jun 21, 2016

Just a heads up -- I was having this same issue and for me this was caused because I was not exposing the correct headers in my cors configuration. For example I had:

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'example.com'

    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

Instead of:

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'example.com'
    resource '*',
      headers: :any,
      expose: ['access-token', 'token-type', 'client', 'expiry', 'uid'],
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

Hope that helps

@Spike980
Copy link

Spike980 commented Jan 1, 2017

Try this fix.
https://github.com/lynndylanhurley/j-toker#possible-complications
It worked for me.

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

7 participants