JSON Web Tokens
This is a modal window.
Das Video konnte nicht geladen werden, da entweder ein Server- oder Netzwerkfehler auftrat oder das Format nicht unterstützt wird.
Formale Metadaten
Titel |
| |
Serientitel | ||
Teil | 39 | |
Anzahl der Teile | 44 | |
Autor | ||
Mitwirkende | ||
Lizenz | CC-Namensnennung - Weitergabe unter gleichen Bedingungen 4.0 International: Sie dürfen das Werk bzw. den Inhalt zu jedem legalen Zweck nutzen, verändern und in unveränderter oder veränderter Form vervielfältigen, verbreiten und öffentlich zugänglich machen, sofern Sie den Namen des Autors/Rechteinhabers in der von ihm festgelegten Weise nennen und das Werk bzw. diesen Inhalt auch in veränderter Form nur unter den Bedingungen dieser Lizenz weitergeben. | |
Identifikatoren | 10.5446/32839 (DOI) | |
Herausgeber | ||
Erscheinungsjahr | ||
Sprache |
Inhaltliche Metadaten
Fachgebiet | ||
Genre | ||
Abstract |
|
DjangoCon US 201439 / 44
2
3
7
8
10
11
13
14
18
26
29
32
38
39
42
43
00:00
Token-RingSummierbarkeitSkalarproduktPhysikalische TheorieW3C-StandardComputeranimation
00:34
DatenfeldHalbleiterspeicherOpen SourceKollaboration <Informatik>Rechter WinkelProdukt <Mathematik>Web logClientProjektive EbeneQuick-SortSystemverwaltungComputeranimation
01:24
InformationCASE <Informatik>Token-RingZahlenbereichW3C-StandardInhalt <Mathematik>Service providerKonvexe MengeSingle Sign-OnComputeranimation
01:44
InformationMultiplikationsoperatorQuellcodeStandardabweichungDatenbankAuthentifikationKartesische KoordinatenCookie <Internet>Quick-SortHumanoider RoboterW3C-StandardGrenzschichtablösungMobiles InternetServerWurm <Informatik>Analytische FortsetzungTypentheorieREST <Informatik>E-MailWeb SiteInhalt <Mathematik>Web ServicesWort <Informatik>IntegralBildgebendes VerfahrenTVD-VerfahrenCASE <Informatik>VerschlingungDomain <Netzwerk>MaschinensprachePasswortMini-DiscEinfach zusammenhängender RaumGebäude <Mathematik>Ein-AusgabeApp <Programm>Rechter WinkelToken-RingURLTelekommunikationComputeranimation
05:23
W3C-StandardStandardabweichungElektronische UnterschriftObjekt <Kategorie>Arithmetisches MittelGoogolTabelleComputeranimation
05:48
Kartesische KoordinatenEinfach zusammenhängender RaumOffene MengeRuhmasseSystemaufrufMereologieComputeranimation
06:13
W3C-StandardComputersicherheitMessage-PassingChiffrierungObjekt <Kategorie>Selbst organisierendes SystemKryptologieIdentifizierbarkeitAlgorithmusComputeranimationXML
06:38
Wort <Informatik>SchlüsselverwaltungW3C-StandardDatenstrukturAutomatische HandlungsplanungMereologieArithmetisches MittelComputeranimation
07:05
Elektronische UnterschriftInformationPasswortDatenstrukturLokales MinimumWurm <Informatik>W3C-StandardComputeranimation
07:38
KonstanteSkriptspracheDatenstrukturUmwandlungsenthalpieBetafunktionWurm <Informatik>ChiffrierungInhalt <Mathematik>Computeranimation
08:01
StandardabweichungToken-RingBitWeb-SeiteE-MailWurm <Informatik>InternetworkingDiagrammCASE <Informatik>MereologieProgrammbibliothekZeichenketteTypentheorieData DictionaryElektronische UnterschriftBimodulMultiplikationsoperatorCodierung <Programmierung>GleichheitszeichenSchlüsselverwaltungAlgorithmusAlgebraisches ModellW3C-StandardObjekt <Kategorie>GeradeGraphVariableBildschirmmaskeZellularer AutomatGüte der AnpassungGewicht <Ausgleichsrechnung>Kette <Mathematik>ValiditätWellenpaketEndliche ModelltheorieTechnische OptikFrequenzProgrammiergerätBasis <Mathematik>Quick-SortStichprobenumfangProgrammierungAtomarität <Informatik>Computeranimation
14:50
Data DictionaryProgrammbibliothekWurm <Informatik>VersionsverwaltungE-MailAutorisierungToken-RingPasswortLoginClientAuthentifikationW3C-StandardAusnahmebehandlungMatchingElektronische UnterschriftSichtenkonzeptFramework <Informatik>Klasse <Mathematik>Installation <Informatik>SchlüsselverwaltungProjektive EbeneURLZeichenketteWeb-SeiteApp <Programm>InformationsspeicherungMultiplikationsoperatorCASE <Informatik>StandardabweichungGruppenoperationAlgorithmusGeradeMessage-PassingARM <Computerarchitektur>MAPFormale SpracheHilfesystemBetafunktionPuffer <Netzplantechnik>CodeMinimalgradGebäude <Mathematik>SprachsyntheseVorhersagbarkeitMobiles InternetSingle Sign-OnAggregatzustandIndexberechnungCookie <Internet>ComputersicherheitInformationAbstandCluster <Rechnernetz>Demoszene <Programmierung>EreignishorizontStapeldateiLogischer SchlussXMLComputeranimation
21:29
Prozess <Informatik>AutorisierungFramework <Informatik>RechenschieberSelbst organisierendes SystemProdukt <Mathematik>Computeranimation
22:19
Computeranimation
Transkript: Englisch(automatisch erzeugt)
00:23
Is it good? Cool, thank you. 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,
00:40
and it's summer all year long. So if you ever get too cold in winter, you'll feel, you'll feel failure to come down. I work, I'm co-founder and CDO at Limp. We do Django, EmberJS, BackboneJS consulting for all kinds of clients. We also have a few products of our own, mostly around team collaboration.
01:00
You can check them out at limp.io. I'm also a collaborator, I have a couple of open-source projects of 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.
01:25
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.
01:41
Some that I find useful for my use cases are single sign-on, where you want to separate authentication 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,
02:01
and you have users, you've probably implemented reset your password workflow where the user receives an email, they click on a link that redirects them to a form, and then they enter their password. These links usually contain a token that identifies that user, right? So, in my case, I've always tend to generate these tokens
02:23
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,
02:42
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
03:02
of implementing server-side authentication for a client-side app, you know, a JavaScript-heavy client-side app, and an API. The traditional one is cookie-based authentication, where you have a server-side cookie that authenticates the user on every request. And then there's the most modern way, let's say,
03:25
which is token-based authentication, which relies on a signed token that is sent to the 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
03:41
and cross-oriented requests, those two don't usually play nicely along. But when you have token-based authentication, you're allowed to make HS calls to any server on any domain, because you're only using HTTP headers. The other cool thing is that
04:00
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, you know, 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,
04:21
right from a CDN, and just have your server be a REST API that only serves, you know, 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 trash those types of attacks off, sorry.
04:46
It also simplifies mobile native applications that require authentication. When you're using, like, 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,
05:03
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.
05:23
So what is Data Web Tokens? As defined by the IETF, the Internet Enduring Task Force, it's a compact neural safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object
05:40
that is digitally signed using JSON Web Signature. 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.
06:01
But JWT is part of a bigger standard called, I don't know how to pronounce this, I'm gonna 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,
06:21
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 JWK or JSON Web Key,
06:42
which is a JSON data structure that represents a cryptographic key. And then we have JWT, or JSON Web Token, like I already said, that is a compact neural safe means of representing a claim to be transferred between two parties. These claims can be digitally signed and or encrypted.
07:03
We have JWS, or JSON Web Signature, which represents content secured with a digital signature using JSON-based data structures. This signature prevents tampering of your payload
07:22
and use with HTTPS prevents man-in-the-middle attacks. But if your payload actually contains sensitive information of the user, like password or any personally identifiable information, you should and need to actually encrypt them using JWE or JSON Web Encryption,
07:42
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 and read data, this specification will actually tell you how to do it.
08:01
But today, it's all about JWT. And how does it actually work? Well, there's the Internet draft that was authored by Michael Jones from Microsoft. That's around 30, 33 pages. It contains all there is to know about JSON Web Tokens,
08:21
and you should definitely check it out. But to make it a little bit shorter, I'm gonna show you the basics on how to create a JSON Web Token just using the Python standard library. Note, you shouldn't be doing this yourself. There are many third-party libraries out there
08:40
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 Web Token looks like. It actually has three parts, which are base64 encoded strings with all trailing equal signs omitted.
09:02
And they're separated by periods. So now, I'm gonna be using this diagram to actually help us across building our token. In this diagram, the green represents a header, which specifies the algorithm we'll be using to sign our token.
09:20
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 TYP key or type
09:41
that indicates that this object is in fact a JSON Web Token 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 SHAT56.
10:04
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 SHAT56 algorithm, so we're gonna import that algorithm from the hashlib module.
10:22
Then, since our strings are actually base64 encoded string and they're safe for URLs, we'll actually be using the urlsafe base64 encode module from the, sorry, method for the base64 module. The first thing we're actually gonna be doing
10:41
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 urlsafe base64 encode a string and we omit any equal signs from the end. If we were to, this header value there
11:02
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,
11:22
which, the token that contains the payload. That's the blue part. In this case, our payload just contains a key, user ID and its value. So similarly to how we already generated our header, we'll be creating a JSON string from our payload,
11:41
which contains a user ID and its value. We'll then create a urlsafe base64 encode a 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, will look like this.
12:04
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.
12:21
In this case, my secret key is abc123. That's not very secure, but it'll 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.
12:42
And then we use our chosen algorithm, which for this example is hmac-shots56. We create a urlsafe base64 encoded string from this hmac-objects digest. And we omit, again, any trailing equal signs. So if you were to take that token variable,
13:05
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.
13:22
But like I said, you probably don't wanna do this yourself every time. 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.
13:40
So just to be clear, if we wanted to decode the token we just created, we'd just reverse 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
14:01
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.
14:24
Pip installed 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.encode,
14:41
send our payload dictionary, use our 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 decode, send in our token string, use the same secret key,
15:00
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 will let you know about it so you can handle it. It also supports five other algorithms. We just saw HMAC 256,
15:22
but you can also use RSA keys and other other 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.
15:43
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, if you use Django and you want to use JSON web tokens for authentication, I'd just build a package that provides
16:01
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 couple work done on it. So basically how it works is that it provides a view
16:22
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.
16:44
It's already in PyPipe, so you can install it, pip install django-jwt. 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,
17:01
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 token auth and page mix-in on your class-based view. In this case, our restricted view
17:21
actually returns a data string with the 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 returns a token. So that's our first URL there.
17:41
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 on GitHub. I'd gladly appreciate it. Now, if you're using Django REST Framework,
18:00
we've had a couple of talks on that, and maybe some of you are already using Django REST 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 jango-rest-framework-jwc. And it works similarly to the one we saw, obviously.
18:23
That was based off on this one. So it provides an authentication class called JSON web token authentication, which if you've seen or worked with Django REST Framework before, you'd plug it into your view's authentication classes,
18:40
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 if you're logging in. So that's how we do it. And then a brief example of JavaScript
19:03
for a JavaScript client using jQuery. We'd first post to our login URL, sending our username and password. It returns, and it will return our token.
19:23
So we can use that and send it on the authorization HTTP header to authenticate our GET request to slash restricted. That probably would return the success callback, and if you were to go do a console log on that, you'd see your foo, bar, JSON string.
19:47
Yesterday, or I think yesterday, I released version 1.0.1, which contains support for Django 1.7. This library's much more mature. It's much more well-tested, so you can still get involved
20:02
and help shape the future of it. So a brief recap of why JSON web tokens. It's standard, and it's easy. I've read a lot of other standards
20:20
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,
20:41
not only for Python, but for Ruby, Node, Go. It works great for single sign-on scenarios. It's also cool for action links, and my preferred use case is for authentication.
21:00
You don't have to struggle with cookies, cross-orient 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 hosted on CDN is so much prettier and faster and more performant,
21:24
and it also simplifies mobile and WebSocket's authentication. I also wanted to point out that I am leading a Django REST framework sprint starting tomorrow. We are backed by Django framework's original author, Tom Christie, so if you wanna get your hands down
21:43
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 this slide at that URL.