What is JWT and what is it for?

I saw in some comment here on the site, in some question, talking about JWT to solve an authentication problem. I had seen the term vaguely before and I thought it was something from Java (hehehe).

However, taking a look at jwt.io , I realized it was a very different thing.

So I'll ask:

  • What is JWT? Is it a library? A specification?

  • So that will it do?

Author: Wallace Maxters, 2016-09-26

1 answers

JWT, in Computer Science, may refer to:

JWT authentication

JWT (JSON Web Token), with the T in uppercase, it is a data transfer system that can be sent via URL, POST or in an HTTP header (header) in a "secure" way, this information is digitally signed, for example signed with the algorithm HMAC , or a public/private key pair using RSA.

An example of a situation that can be used is authentication, once the user is logged in, each request that comes will include JWT, allowing the user to continue accessing services and resources that are have been released with such a token (Single sign-on (SSO)).

The structure of the JWT is in 3 parts divided by points:

  • Header

    Consists of 2 parts usually, the type of the token, which is JWT and the type of the HASH algorithm, such as HMAC SHA256 or RSA, example:

    {
      "alg": "HS256",
      "typ": "JWT"
    }
    

    This will be the first part of base64 encoded JSON to form the JWT

  • Payload (load data or data sent)

    This is the second part of the token, it contains the "requests". This "requests" are statements about an entity (usually the user) and additional metadata and there are 3 types: reserved, public , E private claims . An example:

    {
      "sub": "1234567890",
      "name": "John Doe",
      "admin": true
    }
    
  • Signature

    To generate the signature you must use the header and the Payload encoding them, using the algorithm defined in the header and sign, in the example of the header we use HS256 (HMAC SHA256), then it should be something like:

    HMACSHA256(
      base64UrlEncode(Cabeçalho) + "." +
      base64UrlEncode(Payload),
      secret)
    

    Signature is used to verify that the sender of the "JWT", it is really" who " it claims to be and also to verify that the message has not been changed along the way.

The result would be something like:

(Cabeçalho em base64).(Payload em base64).(Assinatura em base64)

An example of sending via header in HTTP:

GET /foo/bar HTTP/1.1
Host: www.exemplo.com
Authorization: Bearer (Cabeçalho em base64).(Payload em base64).(Assinatura em base64)

I.e. being something that is transmitted via HTTP can be used with any language that supports the minimum requirements to generate the TOKEN and send an HTTP request, such as Java, C#, PHP, Python.

Site: https://jwt.io


JWT and Java

There is a JWt (i.e. Java web toolkit , pronounced "jay-witty") that is in Java (note that in this case the t is tiny) and has no connection with JWT , it is a framework aimed at web development.

It is similar to other web frameworks, however you can develop almost everything directly in Java and it will generate the HTML and Javascript part, except that it has several components and the ability to extend them modifies them.

A Hello World for example:

Src / HelloMain.java :

package eu.webtoolkit.jwt.examples.hello;

import eu.webtoolkit.jwt.WApplication;
import eu.webtoolkit.jwt.WEnvironment;
import eu.webtoolkit.jwt.WtServlet;

public class HelloMain extends WtServlet {
    private static final long serialVersionUID = 1L;

    public HelloMain() {
        super();
    }

    @Override
    public WApplication createApplication(WEnvironment env) {
        /*
         * You could read information from the environment to decide whether the
         * user has permission to start a new application
         */
        return new HelloApplication(env);
    }
}

Src / HelloApplication.java:

package eu.webtoolkit.jwt.examples.hello;

import eu.webtoolkit.jwt.Side;
import eu.webtoolkit.jwt.Signal;
import eu.webtoolkit.jwt.WApplication;
import eu.webtoolkit.jwt.WBreak;
import eu.webtoolkit.jwt.WEnvironment;
import eu.webtoolkit.jwt.WLineEdit;
import eu.webtoolkit.jwt.WPushButton;
import eu.webtoolkit.jwt.WText;
public class HelloApplication extends WApplication {
    public HelloApplication(WEnvironment env) {
        super(env);

        setTitle("Hello world");

        getRoot().addWidget(new WText("Your name, please ? "));
        final WLineEdit nameEdit = new WLineEdit(getRoot());
        nameEdit.setFocus();

        WPushButton button = new WPushButton("Greet me.", getRoot());
        button.setMargin(5, Side.Left);

        getRoot().addWidget(new WBreak());

        final WText greeting = new WText(getRoot());

        button.clicked().addListener(this, new Signal.Listener() {
            public void trigger() {
                greeting.setText("Hello there, " + nameEdit.getText());
            }
        });
    }
}

It generates something like (Of course it also varies as you configure the project):

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<link rel="shortcut icon" href="/favicon.ico">

<meta name="robots" content="noindex, nofollow">
<title></title>
<!--[if gte IE 6]>
<style type="text/css">
v\:* { behavior:url(#default#VML); position:absolute }
</style>
<script id="ie-deferred-loader" defer="defer" src="//:"></script>
<![endif]-->
<script>
/*<![CDATA[*/
window.onresize=function(){};
function loadScript(a,l){var r=document.getElementsByTagName("head")[0],t=/firefox\/(\d+)\./.exec(navigator.userAgent.toLowerCase());if(t&&t[1]>=20){var m=new XMLHttpRequest;m.open("GET",a,true);m.onreadystatechange=function(){if(m.readyState==4){var u=document.createElement("script");u.type="text/javascript";u.innerHTML=m.responseText;r.appendChild(u);l&&l()}};m.send(null)}else{var g=document.createElement("script");if(l)if(g.readyState)g.onreadystatechange=function(){if(g.readyState=="loaded"||
g.readyState=="complete"){g.onreadystatechange=null;l()}};else g.onload=function(){l()};g.setAttribute("src",a);r.appendChild(g)}};
(function(){function a(){function l(){return Math.round(Math.random()*1E6)+724045511}function r(c){if(h.location.replace)h.location.replace(c);else h.location.href=c}function t(){var c=p.getElementById("Wt-form");if(c!=null)c.style.visibility="hidden";else setTimeout(t,10)}function m(){var c=window.location.search;if(c.length>1&&c.charAt(0)=="?")c=c.substr(1);return c.split("&")}function g(c){var q,j,e,n;j=m();q=0;for(n=j.length;q<n;q++){e=j[q].split("=");if(e.length>=2)if(e[0]===c)return unescape(e[1])}return null}
function u(c,q){var j,e,n,y,z=false;e=m();j=0;for(y=e.length;j<y;j++){n=e[j].split("=");if(n.length>=2)if(n[0]===c){n[1]=escape(q);e[j]=n.join("=");z=true;break}}z||e.push(c+"="+escape(q));return"?"+e.join("&")+window.location.hash}var p=document,h=window;try{p.execCommand("BackgroundImageCache",false,true)}catch(B){}h.opera&&h.opera.setOverrideHistoryNavigationMode("compatible");var i='',d=h.location.pathname;h.opera||(d=decodeURIComponent(d));if(i.length>0){var b=d.lastIndexOf(i);if(b!=
-1)d=d.substr(0,b)+d.substr(b+i.length)}i="&deployPath="+encodeURIComponent(d);var o=h.XMLHttpRequest||h.ActiveXObject,k=true;d=new Date;d.setTime(d.getTime()+1E3);;p.cookie="jscookietest=valid";k=k||false&&p.cookie.indexOf("jscookietest=valid")!=-1;p.cookie="jscookietest=valid;expires=Thu, 01 Jan 1970 00:00:00 GMT";p.cookie="WtTestCookie=ok;path=/;expires="+d.toGMTString();;b=h.location.hash;if(b.length>0)b=b.substr(1);var f=
b.indexOf("?");if(f!=-1)b=b.substr(0,f);f=navigator.userAgent.toLowerCase();if(f.indexOf("gecko")==-1||f.indexOf("webkit")!=-1)b=unescape(b);f="";if(screen.deviceXDPI!=screen.logicalXDPI)f="&scale="+screen.deviceXDPI/screen.logicalXDPI;;if(window.WebGLRenderingContext){var v=document.createElement("canvas"),s=null;try{s=v.getContext("webgl",{antialias:true})}catch(C){}if(s==null)try{s=v.getContext("experimental-webgl")}catch(D){}if(s!=null)f+="&webGL=true"};f+=
"&scrW="+screen.width+"&scrH="+screen.height;var w='/jwt-hello/;jsessionid=F4619EEEB03D1B761518BFEAF5306B9D?wtd=F4619EEEB03D1B761518BFEAF5306B9D'+"&sid="+-1435776466;s=(v=!!(window.history&&window.history.pushState))?"&htmlHistory=true":"";var A=(new Date).getTimezoneOffset();f+="&tz="+-A;if(k=!k||!o)if(g("wtd")==="F4619EEEB03D1B761518BFEAF5306B9D")k=false;if(k)if(v)r(u("wtd","F4619EEEB03D1B761518BFEAF5306B9D"));else{i=b.length>1&&b.charAt(0)=="/"?b:'';if(i.length>0)w+="#"+i;r(w)}else if(o){o='';k="";if(!v&&o.length>1){;if(o.charAt(0)=="#")o="../"+o;r(o)}else{if(b.length>1&&b.charAt(0)=="/"){k="&_="+encodeURIComponent(b);};var x=k+f+s+i;;loadScript(w+x+"&request=script&rand="+l(),null);;}}}setTimeout(a,0)})();

/* ]]> */
</script>
<noscript><meta http-equiv="refresh" content="0; url=/jwt-hello/;jsessionid=F4619EEEB03D1B761518BFEAF5306B9D?wtd=F4619EEEB03D1B761518BFEAF5306B9D&amp;js=no"></noscript>
<style type="text/css" id="Wt-inline-css"></style>
</head>
<body>
<!--[if lt IE 8]>
<iframe id="Wt-history-iframe" src="/jwt-hello/;jsessionid=F4619EEEB03D1B761518BFEAF5306B9D?wtd=F4619EEEB03D1B761518BFEAF5306B9D&amp;request=resource&amp;resource=blank"
 style="position:absolute;top:0;left:0;width:1px;height:1px;visibility:hidden;">
</iframe>
<![endif]-->
<input id="Wt-history-field" type="hidden"/>
<noscript>
  <a href="/jwt-hello/;jsessionid=F4619EEEB03D1B761518BFEAF5306B9D?wtd=F4619EEEB03D1B761518BFEAF5306B9D&amp;js=no">Plain HTML version</a>

<link href="/jwt-hello/;jsessionid=F4619EEEB03D1B761518BFEAF5306B9D?wtd=F4619EEEB03D1B761518BFEAF5306B9D&amp;request=style&amp;page=1&amp;js=no" rel="stylesheet"
      type="text/css" >

</noscript>

<link href="/jwt-hello/;jsessionid=F4619EEEB03D1B761518BFEAF5306B9D?wtd=F4619EEEB03D1B761518BFEAF5306B9D&amp;request=style&amp;page=1" rel="stylesheet"
      type="text/css" >

<!--[if gte IE 6]>
<script type="text/javascript">
document.namespaces.add("v","urn:schemas-microsoft-com:vml","#default#VML");
</script>
<![endif]-->
<script type="text/javascript">
/*<![CDATA[*/
setTimeout(function() {
if (typeof $ !== 'undefined')
  $(document).ready(function() { Wt._p_.load(true);});
}, 0);
/* ]]> */
</script>
</body>
</html>

Site: https://www.webtoolkit.eu/jwt

 56
Author: Guilherme Nascimento, 2017-11-09 14:44:28