What is it and what is JWT for?

Asked

Viewed 7,183 times

51

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 something very different.

Then I’ll ask:

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

  • What good is?

  • 3

    I could swear it was something to do with java.

  • 3

    If it were to Java I would know answer :P

  • 3

    When I read JWT the first thing that came to mind was Java :P

  • Basically it is an encrypted token for authentication that contains the user it is possible to put an "expiration time" for the token.

  • Related: http://answall.com/questions/143304/onde-o-jwt-guarda-os-tokens?rq=1

  • It seems that the JWT has some flaws, which deserve further attention. https://news.ycombinator.com/item?id=13865459

Show 1 more comment

1 answer

56


The JWT, in computer science, may refer to:

JWT authentication

JWT (JSON Web Token), with the uppercase T, 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 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 features that are released with such a token (Single Sign-on (SSO)).

The JWT structure is in 3 parts divided by points:

  • Header

    It consists of 2 parts usually, the token type, which is JWT and the HASH algorithm type, for example HMAC SHA256 or RSA, example:

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

    This will be the first part of JSON coded in Base64 to form JWT

  • Payload (load of data or data sent)

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

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

    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), so it should look something like:

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

    The signature is used to verify that the "JWT" sender is actually "who" it is said to be and also to check 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 header upload to HTTP:

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

That is because it is 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.

Website: https://jwt.io


Jwt and Java

There is a Jwt (that is to say Java web Toolkit, is pronounced "Jay-Witty") which is in Java (note that in this case t is minuscule) and has no connection with the 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, outside it has several components and the ability to extend them modify 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 according to the project configuration):

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

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

  • Cool as your reply @Guilherme, today I watched a video that one of the main features of it is the standardization of requests between different applications for identification of the browser, device and other application. I think you missed the answer :D

  • 1

    @Marconi yes, I agree, but I think it has to be something more elaborate to explain exactly what this standardization is, in this case the RFC link probably already explains this well https://tools.ietf.org/html/rfc7519, so I promise to edit with these details soon.

  • 1

    @Guilhermenascimento, I don’t want to cause controversy, but I’m beginning to understand JWT now. According to the above text Um exemplo de situação que ele pode ser usado é a autenticação, but looking at the text of the official page I ended up noticing that it is not used for authentication, although it is used after authentication and yes used as authorization according to the text of the site https://jwt.io/introduction/ in the part When should you use JSON Web Tokens?. I don’t know if this is relevant information or if my note makes sense in the explanation, but it stays as an observation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.