技術ブログ |
Developers.IO |
Raspberry PiとNode-REDでSwitchBotの温湿度計データを取得する |
https://dev.classmethod.jp/articles/raspberry-pi_node-red_switchbot/
|
kobayashi |
2021-10-30 21:30:16 |
海外TECH |
DEV Community |
JWTs explained with code examples |
https://dev.to/propelauth/jwts-explained-with-code-examples-3k29
|
JWTs explained with code examplesThe Wikipedia description of a JSON Web Token JWT is JSON Web Token is a proposed Internet standard for creating data with optional signature and or optional encryption whose payload holds JSON that asserts some number of claims However this definition says a lot without really saying a lot When I m trying to understand a concept I like to play around with relevant libraries We ll try this out with JWTs using the popular javascript library jsonwebtoken Creating a JWTThe first thing the docs mention is that the sign function returns a JWT and the only required arguments are some JSON and a string called secret const jwtLibrary require jsonwebtoken The only arguments we need are a secret value and some JSONconst json key value key value const secret shhhhh Ignore the options for now we ll check them laterconst jwt jwtLibrary sign json secret console log JWT jwt JWT eyJhbGciOiJIUzINiIsInRcCIIkpXVCJ eyJrZXkiOiJYWxZSIsImtleTIiOiJYWxZTIiLCJpYXQiOjEMzQxNzgxMTB vnXMoxwQHVsRsvYpLaEqFFqZ NExQMXBgPMkThis is our first look at a what a JWT looks like Using a JWTWhat can we do with this JWT The library has two other methods verify and decode It lists verify first so we ll try that first From previous exampleconst jwt eyJhbGciOiJIUzINiIsInRcCIIkpXVCJ eyJrZXkiOiJYWxZSIsImtleTIiOiJYWxZTIiLCJpYXQiOjEMzQxNzgxMTB vnXMoxwQHVsRsvYpLaEqFFqZ NExQMXBgPMk const secret shhhhh Ignore the options for now we ll check them laterconst verifyResult jwtLibrary verify jwt secret console log verifyResult verifyResult verifyResult key value key value iat It looks like we got back the JSON that we specified above plus an extra entry iat The docs say that iat is short for issued at and is a unix timestamp of when the JWT was created What happens if we used the wrong secret const jwt eyJhbGciOiJIUzINiIsInRcCIIkpXVCJ eyJrZXkiOiJYWxZSIsImtleTIiOiJYWxZTIiLCJpYXQiOjEMzQxNzgxMTB vnXMoxwQHVsRsvYpLaEqFFqZ NExQMXBgPMk const incorrectSecret thisiswrong const verifyResult jwtLibrary verify jwt incorrectSecret JsonWebTokenError invalid signatureUnsurprisingly we get an error So far we can determine that a JWT somehow encodes the JSON value that we passed in along with other metadata iat Later on we can check that a JWT was created with a specific secret and get back that encoded JSON What about the decode method From previous exampleconst jwt eyJhbGciOiJIUzINiIsInRcCIIkpXVCJ eyJrZXkiOiJYWxZSIsImtleTIiOiJYWxZTIiLCJpYXQiOjEMzQxNzgxMTB vnXMoxwQHVsRsvYpLaEqFFqZ NExQMXBgPMk const decodeResult jwtLibrary decode jwt console log decodeResult decodeResult decodeResult key value key value iat This is kind of strange We didn t pass in the secret but we still got back the original JSON and iat There s a warning on the method in the docs which gives us a hint about what s going on Warning This will not verify whether the signature is valid You should not use this for untrusted messages You most likely want to use jwt verify instead This tells us something important The JSON within the JWT is not encrypted If we store anything sensitive in a JWT anyone could read it even if they don t have the secret Where might this be useful A quick recap on what we ve learned A JWT can be created with JSON and a secretAnyone can get the JSON out of the JWT even without the secretWe can verify that a JWT was created with a specific secretOne common example is authentication After a user logs in we can create a JWT containing metadata about the user like const jwtLibrary require jsonwebtoken const secret shhhhh function createJwtForUser userId return jwtLibrary sign user id userId secret Users can send us the JWT and we can securely know who sent it function getUserIdForJwt jwt try return jwtLibrary verify jwt secret user id catch err Can more gracefully handle errors return null All we need is our secret and we are confident in the returned user id The only way someone could impersonate a user is if they had our secret so choose something better than shhhhh or if they stole a valid JWT from someone else so make sure to keep them safe Additionally we don t need to maintain any state or query any external services to validate the userIds jsonwebtoken OptionsThe sign function takes in a bunch of options that we have skipped Let s go back and look at some const jwtLibrary require jsonwebtoken const json whatever we want anything const secret shhhhh Specify expiresIn for hconst jwt jwtLibrary sign json secret expiresIn h const verifyResult jwtLibrary verify jwt secret console log verifyResult verifyResult verifyResult whatever we want anything iat exp After adding expiresIn we can see that a new entry was added to the JSON exp exp is another unix timestamp and it s seconds hour after the issued time What happens when the time expires We can either wait an hour or speed things up by specifying a negative expiresAt same as beforeconst jwt jwtLibrary sign json secret expiresIn h const verifyResult jwtLibrary verify jwt secret TokenExpiredError jwt expiredWe get an expected error because the jwt expired an hour ago Why is expiresIn useful We said before that once we create a JWT we can check that it s valid without doing any external lookups The issue with this is once a JWT is created it s valid forever as long as the secret doesn t change exp allows us to bound how long the token is valid for by encoding that information in the JSON itself Note that while this library allows us to specify it in a user friendly way h we could also have just added it directly to the JSON const json whatever we want anything exp Math floor Date now hour in the past const secret shhhhh const jwt jwtLibrary sign json secret const verifyResult jwtLibrary verify jwt secret TokenExpiredError jwt expiredThis is actually how most of the options work They are a nice way to specify entries also known as claims that are added to the JSON The issuer option for example adds a claim iss to the JSON iss is used as an id for whoever created the JWT The party verifying the JWT can check the iss to make sure it came from the source they were expecting const json user id const secret shhhhh const jwt jwtLibrary sign json secret issuer propelauth const verifyNoIssuer jwtLibrary verify jwt secret console log verifyNoIssuer user id iat iss propelauth this works because the library only checks the issuer if you ask it toconst verifyCorrectIssuer jwtLibrary verify jwt secret issuer propelauth console log verifyCorrectIssuer user id iat iss propelauth this works because the issuer matchesconst verifyIncorrectIssuer jwtLibrary verify jwt secret issuer oops console log verifyIncorrectIssuer JsonWebTokenError jwt issuer invalid expected oops this fails because the issuer doesn t matchA complete list of standard fields is available here Almost every JWT library will support checking these standard fields What are algorithms The last thing to explore in this library is the algorithms option There are quite a few supported algorithms in the docs The algorithms ultimately control the signing and verification functions There s a lot we can dig into here but at a high level there are two types of algorithms symmetric and asymmetric The default algorithm HS is symmetric meaning the same secret is used for signing and verifying We saw this above when we passed shhhhh into both sign and verify as the secret This is often used when a service is verifying the JWTs they issue themselves Another common algorithm is RS which is asymmetric In this case a private key is used to sign but a public key is used to verify This is often used when the issuer and verifier are different Anyone with the private key can create valid JWTs so if a service is only verifying JWTs they only need the public key It is good practice to specify the algorithm you are expecting in the verify function jwtLibrary verify jwt secret don t do thisjwtLibrary verify jwt secret algorithms HS do thisWhy does this matter Well unfortunately none is a valid algorithm There have been security flaws in applications when a person creates a fake token but uses the none algorithm which expects there to be no signature Some libraries won t allow none at all since it kind of defeats the purpose of verify Summing upYou should now have a pretty good grasp on JWTs based on this implementation If you want to test your understanding try reading the docs for a different popular JWT library PyJWT is a goodchoice for python folks and see if the interfaces make sense |
2021-10-30 21:38:07 |
Apple |
AppleInsider - Frontpage News |
New HomePod mini colors may go on sale in first week of November |
https://appleinsider.com/articles/21/10/30/new-homepod-mini-colors-may-go-on-sale-in-first-week-of-november?utm_medium=rss
|
New HomePod mini colors may go on sale in first week of NovemberThe new colors of the HomePod mini may become available to order in early November with one insider claiming orders could commence in the first week of the month Apple s Unleashed event took time to profile a trio of new HomePod mini color options set to arrive sometime in November According to one rumor that launch may be just around the corner According to Bloomberg s Mark Gurman on Twitter Apple users should expect the new HomePod mini colors early this week While Gurman doesn t offer an exact date it does seem plausible for Apple to release the smart speaker s new options as early as possible in the month to take advantage of holiday shopping patterns Read more |
2021-10-30 21:15:13 |
海外TECH |
Engadget |
Juno probe provides the first 3D view of Jupiter's atmosphere |
https://www.engadget.com/jupiter-atmosphere-3d-view-juno-probe-210638035.html?src=rss
|
Juno probe provides the first D view of Jupiter x s atmosphereNASA s Juno probe has provided a better deeper look at Jupiter s atmosphere Researchers have produced the first D view of Jupiter s atmospheric layers illustrating how its turbulent clouds and storms work in greater detail than before Most notably it s clearer how cyclones and anticyclones behave They re much taller than expected with the Great Red Spot an anticyclone running miles deep They re either warmer or colder at the top depending on their spin too Juno helped fill out the data using a microwave radiometer that offered a peek below the clouds surfaces For the Great Red Spot the team complemented the radiometer data with the gravity signatures from two close passes The radiometer info also showed Earth like circulation cells in northern and souther hemispheres not to mention ocean like changes in microwave light There are still mysteries left such as the atmospheric mass of the Great Red Spot With that said the D imagery is already producing a more cohesive picture of how jovian planets like Jupiter behave It might not take much more effort to solve more of Jupiter s mysteries |
2021-10-30 21:06:38 |
海外科学 |
NYT > Science |
Will You Be Able to See the Northern Lights This Weekend? |
https://www.nytimes.com/2021/10/30/science/space/aurora-northern-lights.html
|
Will You Be Able to See the Northern Lights This Weekend The dazzling phenomenon could be visible on Saturday night or early Sunday morning experts said depending on the weather and local light pollution |
2021-10-30 21:32:10 |
海外科学 |
NYT > Science |
The COP26 Climate Talks Are Opening. Here’s What to Expect. |
https://www.nytimes.com/2021/10/30/climate/climate-summit-glasgow.html
|
The COP Climate Talks Are Opening Here s What to Expect Some fundamental differences including over money divide the leaders heading to Glasgow The outcome will determine to a large extent how humanity will survive on a hotter planet |
2021-10-30 21:12:32 |
ニュース |
BBC News - Home |
Haverfordwest: Deaths after major River Cleddau rescue operation |
https://www.bbc.co.uk/news/uk-wales-59102136?at_medium=RSS&at_campaign=KARANGA
|
crews |
2021-10-30 21:08:37 |
ニュース |
BBC News - Home |
Covid in Wales: Wrexham church displays angels to honour deaths |
https://www.bbc.co.uk/news/uk-wales-59091179?at_medium=RSS&at_campaign=KARANGA
|
covid |
2021-10-30 21:43:08 |
ニュース |
BBC News - Home |
Aguero taken to hospital with chest injury as Barca draw first match since Koeman sacking |
https://www.bbc.co.uk/sport/football/59106509?at_medium=RSS&at_campaign=KARANGA
|
Aguero taken to hospital with chest injury as Barca draw first match since Koeman sackingSergio Aguero is taken to hospital for tests after suffering what appears to be a chest injury as Barcelona draw their first match since the sacking of Ronald Koeman |
2021-10-30 21:24:20 |
北海道 |
北海道新聞 |
マジシャンのパルト小石氏が死去 「あったまぐるぐる」で人気 |
https://www.hokkaido-np.co.jp/article/606221/
|
死去 |
2021-10-31 06:12:00 |
北海道 |
北海道新聞 |
スーダンで大規模デモ、3人死亡 クーデターに数万人抗議、軍発砲 |
https://www.hokkaido-np.co.jp/article/606198/
|
軍事 |
2021-10-31 06:02:44 |
ビジネス |
東洋経済オンライン |
はやぶさ通過もなんのその、福島ご当地鉄道事情 「乗っているだけで楽しい」絶景路線が勢ぞろい | トラベル最前線 | 東洋経済オンライン |
https://toyokeizai.net/articles/-/465318?utm_source=rss&utm_medium=http&utm_campaign=link_back
|
勢ぞろい |
2021-10-31 06:30:00 |
コメント
コメントを投稿