tymondesigns / jwt-auth

🔐 JSON Web Token Authentication for Laravel & Lumen
https://jwt-auth.com
MIT License
11.31k stars 1.55k forks source link

Questions about JavaScript Package & Authorization header #1293

Open awd22 opened 7 years ago

awd22 commented 7 years ago

I was just wondering, if 'Angular' is required to use this framework. I don't have much experience with JavaScript and I'm trying to just use JQuery to pass authorization headers to HTTP requests. I am having difficulty finding straightforward answers on how to do it in JavaScript. I have included the two lines to the .htaccess file for Apache servers but when I data dump all of the headers, I don't see the authorization header. Any help will be much obliged, Thank You.

kohenkatz commented 7 years ago

Show us some code:

awd22 commented 7 years ago

*.htaccess file

Options -MultiViews RewriteEngine On RewriteCond %{HTTP:Authorization} ^(.*) RewriteRule .* - [e=HTTP_AUTHORIZATION:%{HTTP:Authorization}] # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)/$ /$1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L]
awd22 commented 7 years ago

I'm trying to look for a source on the web on how to pass the token with JavaScript.. I have had no luck finding a sample script that I could build off of. I can see the header in developer tools after using this PHP command: response()->json(['token'=>$token, ])->header('Authorization', 'Bearer ' . $token); I just dont know how to grab the token, attach it to all of the requests after login is authenticated. It's pretty tricky

kohenkatz commented 7 years ago

Did you try the jQuery documentation or searching StackOverflow? There are dozens of examples.

Here's how to get the token when you log in:

$.ajax({
    type: "POST",
    url: '/login'
    data: {username: "username", password: "password"},
}).done(function (response, status, xhr) {
    var jwt = xhr.getResponseHeader("Authorization");
    // Store `jwt` in window.localStorage
}).fail(function (err)  {
    //Error during request
});

Here's an example of how to do a jQuery ajax() request with JWT:

$.ajax({
    type: "POST", //GET, POST, PUT
    url: '/authenticatedService'  //the url to call
    data: yourData,     // POST Data sent to server, if applicable
    contentType: contentType,
    beforeSend: function (xhr) {
        // Replace `getJwtToken()` with your own function, as necessary
        // If you stored the token in localStorage as mentioned above, you should retrieve it there.
        xhr.setRequestHeader("Authorization", 'Bearer '+ getJwtToken());
    }
}).done(function (response) {
    //Response ok
}).fail(function (err)  {
    //Error during request
});
awd22 commented 7 years ago

I appreciate it.. I am going to try to implement it into my project... I will get back to you if I run into problems

awd22 commented 7 years ago

@kohenkatz So I have put 'jwt.auth' in the middleware on the mapWebRoutes function in the RouteServiceProvider file.. So now, basically my web app is broken because it requires a token on the index/landing page. I don't want to use session data at all. Is that possible with this package? Where should I place the AJAX requests at in the project?

kohenkatz commented 7 years ago

@awd22 You should not be using jwt.auth on your web routes, because can't use JWT to load the web page itself unless you put the entire token in the URL as a query string parameter (which is highly not recommended). In general, you should use jwt.auth for api routes only. You have two options:

  1. Allow non-authenticated users to access the page but don't show them any data until they log in. This is the basis of most "Single Page Apps" and is out of scope for this issue.
  2. Use sessions for loading the application webpage itself and use JWT for the API calls. Here's how I did this for one application:

    1. When the user comes to the application, check if they have a session. If yes, then load the application. If not, redirect the user to the login page.
    2. On the login page, when the user submits the form, use an AJAX request to log in (as I showed above). If the login is successful, the server will return a JWT.
    3. Use the JWT to POST to another login endpoint that creates a traditional cookie session and redirects the user back to the application.

It sounds like you are now having an issue with the general design of your application and not with this specific package. StackOverflow is probably a better place to ask about that.

awd22 commented 7 years ago

I have configured session cookies so I'm hoping that is secure enough for all of my users. I will be making an interface in the future for a medical device to connect with and send messages to my app. so I'm going to keep this issue open until I'm ready to start on the medical device api