Consuming JWT in Client side with Jquery

in #utopian-io7 years ago

Repository

https://github.com/jquery/jquery

What Will I Learn?

  • Consuming JWT API with endpoint
  • Ajax Setup Header
  • Make Authorization in headers Ajax
  • Set Cookie for Authorization

Requirements

Difficulty

  • Intermediate

Tutorial Contents

This tutorial I will share how to consume API that uses JWT (JSON Web Token) in authentication. I suggest you follow the tutorial I made earlier about creating API with JWT. because later I will use the API that I have created in the previous tutorial. I will share how APIs are consumed with JWT on JQuery and Vue.
I have created the server in another part of the tutorial about JWT. you can read it in the curriculum available at the bottom of this post.

JWT API with JQuery

There are several stages that we will do to ready to consume JWT:

  • Saves the token on the client side

Because we will use tokens as authentication, of course, we must save tokens on the client side. the question is where will we store the token?.

Where will we store the token?

There are two options we can do to store tokens. ie using local storage or using cookies. but in my opinion, to be more secure I will use cookies. but of course, you can look for other references.

  • Install the Jquery-cookie plugin
    Because we will use cookies, then we need jquery plugins that handle cookies. https://github.com/carhartl/jquery-cookie. we can take the source code. and save it in your javascript file. I have created it in jqueryCookie.js and index.html. We can import the jquery and jquery cookies we have stored in file jqueryCookie.js. We can see the example as follows

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Consuming JWT with Jquery and Vuejs</title>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
    <script type="text/javascript" src="./jqueryCookies.js"></script>
</head>
<body> </body>
</html>

Noted: During this tutorial, I use Mozilla Firefox, because of chrome bit strict with localhost. you can use chrome with the local server like Wamp, Xampp or etc.

  • Make Form Login

I will add a simple login form that will be used for user authentication.

<h1> Consuming JWT with Jquery</h1>
    <form id="form">
        <input type="email" name="email" id="email">
        <input type="password" name="password" id="password">
        <input type="submit" name="submit" value="Log In">
    </form>
  • Make Script for post data
    We will post data to http://localhost: 3000/api/login using Jquery Ajax. We can use the method $.post().

Example:

<script>
        $(document).ready(function{
            //form submit
            $("form").submit(function(event){
                var _email      = $('#email').val();
                var _password   = $('#password').val();
                $.post("http://localhost:3000/api/login",{
                    email:_email, password: _password
                }).done(function(data){
                    $.cookie('token',data.token)
                })
            })
        });
    </script>
  • $("form").submit : We can use the submit method to make a request. we need the ID of the form we will submit. in this tutorial, The Id is the form that we have created in the file index.html < form id = "form" > < /form >
  • $.post(): to post data with the $.post() method, we need two mandatory parameters.

1. The first parameter: The first parameter is the URL or endpoint to be addressed. in this tutorial is local server HTTP:/localhost:3000.
2. The Second parameter: The second parameter is the object that contains the key and value we will post to the endpoint.in this tutorial key and value, we will post is {email: _email, password: _password. The key is email and password. The value is _email and _password from var _email = $('#email').val(); and var _password = $('#password').val();. We can take value from an input with jquery method val() : $('#IDofInput').val()

  • $.cookie('token',data.token): We will save the result from post data to endpoint http:/localhost/api/login, When saving with jquery-cookies there are two mandatory parameters. the first key and the second is the data we will save. in this tutorial the key is 'token' and its value is obtained from data.token. The data comes from the callback function
    .done (function (data). If I do console.log on the data. we will see the contents as follows:

Screenshot_3.png

Using Ajax

We will use the ajax method from jquery to connect with API.

  • Setup Ajax
    We need to create an ajax setup to pass token that is stored in cookies $.cookie('token') as "Authorization" in the headers section.
    Example:

$.ajaxSetup({
    headers:{
        'Authorization': $.cookie('token')
    }
})

  • Get user
    In the previous tutorial we have created an endpoint http:/localhost:3000/api/users. I will create a button with id="getuser" to submit to the endpoint http:/localhost:3000/api/users.
    < button type="submit" id="getuser" >Get User< /button >.

Example:


$('getuser').click(function(){
            $.ajax({
                type    : 'GET',
                url     : 'http:/localhost:3000/api/users',
                success : function(data){
                    console.log(data)
                }
            });
        });

  • type: type is the request method to the server, there are several methods. They are get, post, put, delete, patch or etc.
  • url : url is the endpoint or API that we will go to. 'http:/localhost:3000/api/users'.
  • success : function(data){}: We can do callback function with success: function (data), If ajax succeed we will get callback which is in data. I will do a console log to see results from ajax to endpoint 'http:/localhost:3000/api/users'

Screenshot_4.png

  • Get user profile
    In the previous tutorial we have created an endpoint http:/localhost:3000/api/profile. I will create a button with id="getprofile" to submit to the endpoint http:/localhost:3000/api/profile.
    < button type="submit" id="getprofile" >Get Userdata< /button >.

$('#getprofile').click(function(){
            $.ajax({
                type    : 'GET',
                url     : 'http:/localhost:3000/api/profile',
                success : function(data){
                    console.log(data)
                }
            });
        });

  • type: type is the request method to the server, there are several methods. They are get, post, put, delete, patch or etc.
  • url : url is the endpoint or API that we will go to. 'http:/localhost:3000/api/profile'.
  • success : function(data){}: We can do callback function with success: function (data), If ajax succeed we will get callback which is in data. I will do a console log to see results from ajax to endpoint 'http:/localhost:3000/api/profile'

Screenshot_5.png

Note: make sure the server nodes and mongod databases you have run, as long as you interact with the endpoint or API that we created in the previous tutorial, if you are confused you can follow some tutorials below.

Screenshot_6.png

Curriculum

Sort:  

Your tutorial is well done and with enough useful information, thanks for your contribution.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Fokus Utopian nih kayaknya hha :D

Hi, You Just got an upvote from @steemit.medan, Keep create interesting and original content..!!!
[steemit.medan]

Screen Shot 2018-05-02 at 14.31.56.png

Hey @alfarisi94

Thanks for contributing via Utopian.
We're already looking forward to your next contribution!

Contributing on Utopian
Learn how to contribute on our website or by watching this tutorial on Youtube.

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.22
TRX 0.20
JST 0.034
BTC 91713.09
ETH 3128.30
USDT 1.00
SBD 3.18