 So I'm gonna be talking to you today about JWT or how it's said to actually be pronounced jot or just JSON web tokens. My name is Jose Padilla. I am from Puerto Rico, down in the Caribbean where we have beaches just like this and it's summer all year long. So if you ever get too cold in winter, you'll feel free to come down. I work, I'm co-founder and CDO at Limp. We do Django, AmberJS, BackboneJS, consulting for all kinds of clients. We also have a few products of our own, mostly around team collaboration. You can check them out at Limp.io. I'm also a collaborator. I have a couple of open source projects on my own that you can find on GitHub. That's my username right there. I also tend to blog about startups and tech related experiments of my own whenever I get the chance in my blog right there. So why JSON web tokens? JSON web tokens actually provide us a way to simply send information whose contents can be verified to be trusted and there are a number of scenarios where they actually come in handy. Some that I find useful for my use cases are single sign-on where you want to separate authentication of a server that you can send user information in a trusted way. Also, actual links. If you're running any kind of service that uses email communication method and you have users, you've probably implemented a reset your password workflow where the user receives an email, they click on a link that really directs them to a form and then they enter their password. This links usually contain a token that identifies that user. So in my case, I've always tend to generate these tokens in a myriad of different ways. The cool thing about JWT is that it's a standard that works well for URLs. Anytime that you need to communicate a small payload of information between two sources like via webhooks, this will allow you to actually validate the payload while ensuring its integrity. In other words, you can make sure that the token has not been tampered with. And now, my favorite, token-based authentication. We all know that there are two most common ways of implementing server-side authentication for client-side app, JavaScript heavy client-side app, and an API. The traditional one is cookie-based authentication where you have a server-side cookie that authenticates a user on every request. And then there's the most modern way, let's say, which is token-based authentication, which relies on a signed token that is sent to a server on each request to authenticate the user. Some of the benefits that I actually see for using a token-based approach for authentication are, when you're using cookies and cross-order requests, those two don't usually play nicely along. But when you have token-based authentication, you're allowed to make a test call to any server on any domain because you're only using HTTP headers. The other cool thing is that you don't need to keep a session store. When you're using cookies, you usually have a database where you have your sessions or you have a Mongo or Redis or Memcache as a session store. This also allows you to serve all your static content, your JavaScript, your HTML, your images, your CSS, right from a CDN, and just have your server be a REST API that only serves data content in, like, say, JSON. You also don't need to protect against cross-side request forgery attacks. Since you're using cookies, you can just crash those types of attacks of, sorry. It also simplifies mobile native applications that require authentication when you're using iOS or Android, and you're building mobile apps for that, you usually have to take care of these things called cookie containers, which in my experience have been pretty annoying to work with. It's also very great for authenticating WebSockets. When you have a WebSockets application, applications that use the WebSockets, you have to authenticate the user via HTTP, but then you have to make sure you're authenticating the WebSockets connection as well. So, what is JSON WebSockets? As defined by the IETF, the Internet Enduring Task Force, is a compact URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is digitally signed using JSON WebSignature. The cool thing about this standard is that it's used by companies like Google, Microsoft, Firebase, Send Desk, and by applications like OpenID Connect and Mozilla Persona. But JWT is part of a bigger standard called, I don't know how to pronounce this, I wanna pronounce how I pronounce my name, Jose. We have nothing to do with this. It's actually JavaScript object signing and encryption. The IETF Jose working group is actively standardizing specs for the purpose of adding message security to JSON. So we have things like JWA or JSON Web Algorithms which registers cryptographic algorithms and identifiers that are to be used with the following specifications like JDLUK or JSON Web Key, which is a JSON data structure that represents a cryptographic key. And then we have JWT or JSON WebToken like I already said. That is a compact URL save means of representing a claim to be transferred between two parties. These claims can be digitally signed and or encrypted. We have JWS or JSON WebSignature which represent content secured with a digital signature using JSON-based data structures. This signature prevents tampering of your payload and used with HTTPS prevents man-in-the-middle attacks. But if your payload actually contains sensitive information of the user like password or any personally identified information, you should and need to actually encrypt them using JWT or JSON Web Encryption which represents encrypted content using JSON-based data structure. So basically, if you wanna encrypt JSON data so that only the intended receiver actually can read the payload, can read data, this specification will actually tell you how to do it. But today it's all about JWT and how does it actually work? Well, there's the internet graph that was authored by Michael Jones from Microsoft. That's around about 30, 33 pages. It contains all there is to know about JSON WebTokens and you should definitely check it out. But to make it a little bit shorter, I wanna show you the basics on how to create a JSON WebToken just using the Python standard library. Note, you shouldn't be doing this yourself. There are many third-party libraries out there that actually handle the encoding and decoding of these tokens and handle all the other special cases as well. So this is what a JSON WebToken looks like. It actually has three parts, which are Bay 64 encoded strings with all trailing equals signs omitted. And they're separated by periods. So now I'm gonna be using this diagram to actually help us across building a token. In this diagram, the green represents a header which specifies the algorithm we'll be using to sign our token. The blue part actually represents the payload, the data you want to encode as a token. And the red part represents the signature. So this is an example of a header. It's JSON object containing a TYP key or type. That indicates that this object is in fact a JSON WebToken. And then it also has an algorithm or ALG key that indicates the algorithm we'll be using for the signature. So in this case we'll be using HS256, which actually stands for HMAC Shots of 56. Doing this with the standard library is pretty easy. You'll do some basic imports. You'll import the JSON module, the HMAC module. As I said, we're gonna be using the Shots of 56 algorithm. So we're gonna import that algorithm from the HashLib module. Then since our strings are actually base64 encoded string under save for URLs, we'll actually be using the URL save base64 encode module from the, sorry, method for the base64 module. The first thing we're actually gonna be doing is creating a JSON string from our header dictionary. In this case it contains the type and the algorithm, like I said before. So we create a URL save base64 encoded string and we emit any equal signs from the end. If we were to, this header value there would produce a string that if we will use it to replace our first part of the diagram would look like this. So we've replaced the green part of our diagram with our just generated header string. So now we'll be creating the second part of the payload with the token that contains the payload. It's a blue part. In this case our payload just contains a key, user ID, and it's value. So similarly to how we already generated our header we'll be creating a JSON string from our payload which contains user ID and it's value. We'll then create a URL save base64 encoded string omitting any trailing equal signs. If we were to take that payload variable it will produce a string which will be used in the second part of our token and replaced in our diagram would look like this. So now all that's left is actually creating the signature. To create the signature we need a secret key and the secret key is shared between the two parties that will actually be encoding and decoding this token. In this case my secret key is ABC123 that's not very secure but it will do for now. So we then compute, to compute the signature we take our secret key, our encoded header and payload concatenated by the string. That's that second line there. And then we use our chosen algorithm which for this example is HMAC shots56. We create a URL save base64 encoded string from this HMAC objects digest and we omit again any trailing equal signs. So if we were to take that token variable which actually puts back all our segments together we'll end up with our token. We've just replaced the red part of our diagram with our signature string. But like I said you probably don't wanna do this yourself every time but there are already many third party libraries out there that are already tested and have cool features and actually implement all the cool parts of the spec. So just to be clear if we wanted to decode the token we just created. We just reversed the steps we just did. So we'd first create the signature from the first two parts of our token. Then if the signatures match we'll be able to correctly extract the payload by doing a B64 decode and correctly handling our user ID and our user value. So one of the cool Python libraries that are out there is pyjwt. I happen to be one of the maintainers of it. You could install it from pip, pip install pyjwt and it's way simpler to use. We'll just import it. If we wanted to create a token from our payload which in this case is just the same as before, user ID one, we'd do jwt.ncode, center payload dictionary, user secret key and that would generate the exact same token we just saw. If we wanted to decode that and obtain our original payload dictionary, we'd do jwt.ncode, send in our token string use the same secret key and you'd end up with the same payload dictionary. If the signature actually didn't match because you didn't use the same secret key used to encode the token, this library will raise an exception and I'll let you know about it so you can handle it. It also supports five other algorithms. We just saw hmap256 but you can also use RSA keys and other, I don't know, algorithms. It also supports a cool claim from the standard that lets you add expiration time to these tokens. You can contribute to this project on GitHub. I'd say it's pretty mature. It's got like two years perhaps and it's well tested so check it out. So now you use Django and you'd want to use JSON Web tokens for authentication. I just built a package that provides JSON Web token authentication for Django. I released 0.1 like two days ago I think. So it's definitely pretty, well it's tested but it still needs a whole work done on it. So basically how it works is that it provides a view to authenticate a user. It returns a JSON Web token from the user's username and password and that token can be used to authenticate other requests. So to authenticate a request you'd send the token you just received using the authorization HTTP header. It's already on PyPy so you can install it, pre-install Django-data.ly team. And right now it's pretty simple. It actually provides a mix-in called JSON Web token auth mix-in. If you're using class-based views you can start using this. I should put in there like a decorator or something for those using function-based views but I like class-based views myself so. So you use that JSON Web token which makes an on-your-class-based view. In this case our restricted view actually returns a day's string with a key foo and the value bar. So if you plug in your URLs you can actually use a built-in view that's provided, that's used for actually logging in with the username and password and return to token. So that's our first URL there. And then we have our restricted view URL. Like I said, this is very beta or alpha, I don't know. You can get involved and help shape the future of this project and GitHub. I gladly appreciate it. Now if you're using Django Res Framework we've had a couple of talks on that and maybe some of you are already using Django Res Framework. I actually built this package first. It's a third-party package that provides JSON Web token authentication. You can install it from PIP. PIP install Django Res Framework-JWC. And it works similarly to the one we saw, obviously. That was based off on this one. So it uses a, it provides an authentication class called JSON Web token authentication which if you've seen or worked with Django Res Framework before you plug it into your views authentication classes and that's all you have to do. That view will automatically authenticate any requests coming from a client. Again, it provides a built-in view that you can use to obtain JSON Web tokens which is logging in. So that's how we do it. And then a brief example of JavaScript for a JavaScript client using jQuery. We'd first post to our login URL sending our username and password. It returns and it will turn our token. So we can use that and send it on the authorization HTTP header to authenticate or get requests to slash restricted. That probably would return the success callback and if you were to go to a console log on that, you'd see your foo bar JSON string. I think yesterday I released version 1.0.1 which contains support for Django 1.7. This library is much more mature, it's much more well tested. So you can still get involved and help shape the future of it. Good hope. So a brief recap of why JSON Web tokens, it's standard and it's easy. I've read a lot of other standards on this kind of JSON message security and this one is by far the most easiest to understand and most easiest to actually implement. As we saw, we just implemented half of how it works in a few lines of standard library Python. There are tons of third-party libraries out there, not only for Python, but for Ruby, no, go. It works great for single sign-on scenarios. It's also cool for actual links and my preferred use case is for authentication. You don't have to struggle with cookies, cross-oriented requests, it's stateless so you don't need to session store anymore. You don't have to deal with CSRF tags or anything like that. Having your client-side app all hosting a CDN is so much prettier and faster and more performant and it also simplifies mobile and web-socket authentication. I also wanted to point out that I am leading a Django REST framework sprint starting tomorrow. We were backed by Django REST framework's original author, Tom Christie. So if you wanna get your hands down and help move this product forward, you can find me around the hall and we'll get organized. Thanks, any questions? You're gonna find these slides at that URL.