在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:dwyl/learn-json-web-tokens开源软件地址:https://github.com/dwyl/learn-json-web-tokens开源编程语言:JavaScript 86.8%开源软件介绍:Learn how to use JSON Web Tokens (JWT) for AuthenticationLearn how to use JSON Web Token (JWT) to secure your Web and/or Mobile Application! Why?JSON Web Tokens (JWTs) make it easy to send read-only signed "claims" between services (both internal and external to your app/site). Claims are any bits of data that you want someone else to be able to read and/or verify but not alter.
What?
In EnglishTo identify/authenticate people in your (web/mobile) app, put a standards-based token in the header or url of the page (or API endpoint) which proves the user has logged in and is allowed to access the desired content. example:
What does a JWT Look Like?Tokens are a string of "url safe" characters which encode information. Tokens have three components (separated by periods) (shown here on multiple lines for readability but used as a single string of text)
1. HeaderThe first part of a JWT is an encoded string representation of a simple JavaScript object which describes the token along with the hashing algorithm used. 2. PayloadThe second part of the JWT forms the core of the token. Payload length is proportional to the amount of data you store in the JWT. General rule of thumb is: store the bare minimum in the JWT. 3. SignatureThe third, and final, part of the JWT is a signature generated based on the header (part one) and the body (part two) and will be used to verify that the JWT is valid. What are "Claims"?Claims are the predefined keys and their values:
See: https://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#RegisteredClaimName ExampleLets get stuck in with a simple example. (the full source is in the /example directory)
To play around with the example you can open it in Gitpod (requires OAuth with GitHub). ServerUsing the core node.js http server we create 4 endpoints in /example/server.js:
We have deliberately made server.js as simple as possible for:
Helper MethodsAll the helper methods are kept in /example/lib/helpers.js The two most interesting/relevant methods are (simplified versions shown here): // generate the JWT
function generateToken(req){
return jwt.sign({
auth: 'magic',
agent: req.headers['user-agent'],
exp: Math.floor(new Date().getTime()/1000) + 7*24*60*60; // Note: in seconds!
}, secret); // secret is defined in the environment variable JWT_SECRET
} Which generates our JWT token when the user authenticates (this is then sent back to the client in the Authorization header for use in subsequent requests), and // validate the token supplied in request header
function validate(req, res) {
var token = req.headers.authorization;
try {
var decoded = jwt.verify(token, secret);
} catch (e) {
return authFail(res);
}
if(!decoded || decoded.auth !== 'magic') {
return authFail(res);
} else {
return privado(res, token);
}
} Which checks the JWT supplied by the client is valid, shows private ("privado") content to the requestor if valid and renders the authFail error page if its not. Note: Yes, both these methods are synchronous. But, given that neither of these methods require any I/O or Network requests, its pretty safe to compute them synchronously.
TestsYou may have noticed the [![Build Status][travis-image]][travis-url] badge at the start of this tutorial. This is a sign the author(s) are not just cobbling code together. The tests for both the server routes and helper functions are in: /example/test
Please read through the tests and tell us if anything is unclear! Note: We wrote a basic "mock" of the http req/res objects see: /example/test/mock.js Confused/curious about Mocking? Read When to Mock (by "Uncle Bob") Frequently Asked Questions (FAQ)
Q: If I put the JWT in the URL or Header is it secure?Good question! The quick answer is: No. Unless you are using SSL/TLS (https in your url) to encrypt the connection, sending the Token in-the-clear is always going to be insecure (the token can be intercepted and re-used by a bad person...). A naive "mitigation" is to add verifiable "claims" to the token such as checking that the request came from the same browser (user-agent), IP address or more advanced "browser fingerprints" ... https://programmers.stackexchange.com/a/122385 The solution is to either:
Use-cases for a JWT token in a url are:
Both of these are good candidates for single-use tokens (which expire after they have been clicked). Q: How do we Invalidate sessions?The person using your app has their device (phone/tablet/laptop) stolen. How do you invalidate the token they were using? The idea behind JWT is that the tokens are stateless they can be computed by any node in a cluster and verified without a (slow) request to a database. Store the Token in a Database?LevelDBIf your app is small or you don't want to have to run a Redis server, you can get most of the benefits of Redis by using LevelDB: http://leveldb.org/ We can either store the valid Tokens in the DB or we can store the invalid tokens. Both of these require a round-trip to the DB to check if valid/invalid. So we prefer to store all tokens and update the valid property of the token from true to false. Example record stored in LevelDB "GUID" : {
"auth" : "true",
"created" : "timestamp",
"uid" : "1234"
} We would lookup this record by its GUID: var db = require('level');
db.get(GUID, function(err, record){
// pseudo-code
if(record.auth){
// display private content
} else {
// show error message
}
}); see: example/lib/helpers.js validate method for detail. RedisRedis is the scalable way of storing your tokens. If you are totally new to Redis read:
Redis Scales (provided you have the RAM): https://stackoverflow.com/questions/10478794/more-than-4-billion-key-value-pairs-in-redis
Memcache?Quick answer: use Redis: https://stackoverflow.com/questions/10558465/memcache-vs-redis Q: Returning Visitor (no State Preservation between sessions)Cookies are stored on the client and are sent by the browser to the server on every request. If the person closes their browser, cookies are preserved, so they can continue where they left off without having to log-in again. However, cookies will be sent on all requests that match the path and issuing domain, including those for images and css, where it isn't needed.
Browser-based ApplicationsThere are two options for storing your JWTs:
Useful Links
Programmatic (API) AccessOther services accessing your API will have to store the token in a retrieval system (e.g: Redis or SQLite for mobile apps) and send the token back on each request. How to generate secret key?
Since JSON Web Tokens (JWT) do not have to be signed using asymmetric encryption you do not have to generate your secret key using ssh-keygen. You can just as easily use a strong password e.g: https://www.grc.com/passwords.htm provided it's long and random. The chance of collision (and thus someone being able to modify the payload, adding or modifying claims, and create a valid signature) is pretty low. And if you join two of those Strong Passwords (strings) together, you'll have a 128bit ASCII String. So the chances of collision are less than the number of atoms in the universe. To quickly and easily create a secret key using Node's crypto library, run this command.
In other words, you can use an RSA key, but you don't have to. The main thing you need to remember is: don't share the key with people who are not in your core ("DevOps Team") or accidentally publish it by committing it to GitHub! Which Node.js Module?A search for "JSON Web Token" on NPM: https://www.npmjs.com/search?q=json+web+token yields many results! Building a Web App with Hapi.js?In our efforts to simplify using JWTs in Hapi.js apps, we wrote this module: https://github.com/dwyl/hapi-auth-jwt2 General Use in Other Node.js ProjectsWe highly recommend using the jsonwebtoken module made by our friends @auth0 (the identity/authentication experts):
Another great option is: https://github.com/joaquimserafim/json-web-token by our friend @joaquimserafim Essential Reading (Background)
Further Reading (Recommended)
Thanks for Learning with Us!If you found this quick guide useful, please star it on GitHub! and re-tweet to share it with others: https://twitter.com/olizilla/status/626487231860080640 |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论