What is and what is JWT for?

45

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 loosely before and I thought it was something Java (hehehe).

However, by looking at jwt.io , I realized that it was a very different thing.

Then I'll ask:

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

  • What's the use?

asked by anonymous 26.09.2016 / 18:24

1 answer

50

JWT, in computing, can refer to:

JWT authentication

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

An example of a situation that it can use is authentication, once the user is logged in, every request that comes will include JWT, allowing the user to continue accessing services and resources that are freed with such a token Single sign-on (SSO).

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

  • Header

    It consists of 2 parts generally, the type of the token, which is JWT and the type of the HASH algorithm, such as HMAC SHA256 or RSA , eg

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

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

  • Payload (upload data or uploaded data)

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

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

    In order to generate the signature you must use the Header and Payload encoding them, using the algorithm defined in the header and sign, in the Header example we use HS256 (HMAC SHA256), then something like:

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

    The signature is used to verify that the "JWT" issuer is actually "who" it is said to be and also to verify that the message has not changed along the way.

The result would be something like:

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

An example header 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)

In other words, because it is transmitted via HTTP, it can be used with any language that supports the minimum requirements to generate TOKEN and send an HTTP request, such as Java, C #, PHP, Python.

Site: link

JWt and Java

There is a JWt (ie Java web toolkit , it is pronounced "jay-witty") which is in Java (note that in this case ot is minuscule) has no connection to JWT , it is a framework for 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, which 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 the project is configured):

<!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: link

    
26.09.2016 / 19:58