JsonWebTokens ppt - explains JWT, JWS , JWE Tokens

nagarajapallafl 35 views 25 slides Sep 20, 2024
Slide 1
Slide 1 of 25
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25

About This Presentation

JSON Web Token presentation


Slide Content

JSON Web Token History JWT Token Sample Client side Session/Stateless session Algorithms used in JWT JWS and JWE tokens Use cases and Best practices

2001 - OASIS group started working on XML framework for exchanging authentication and authorization information SAML 1 - 2002 SAML 2 - 2005 XML Signature, XML Encryption OpenId Connect – ID Token format is JWT 2011 - JOSE (JSON Object Signing and Encryption) Group formed 2013 - Series of draft RFCs for JWT, JWS, JWE, JWK, JWA JWS - JSON Web Signature JWE - JSON Web Encryption

JWT – Signature Token Compact Format

Use case : Client Side/Stateless Session

Algorithms used Hashing (SHA)

----- BEGIN RSA PRIVATE KEY----- MIIBPAIBAAJBAL76snni9v2GMPhTMTUASojXKJLeX8D5qmOo/z7guvIMyioQCEXf 0YiLgCUsFeVy7YT1jHHoRGa1vNUUlFMuH6sCAwEAAQJBAIE96RBhT2LMsFEtA4zp sIcgjD2wLb7LdsrQ8ENeFEV+wcjc8LCqP0RRPFmX5nT3ixeG3I56l/vLwZP54Qm2 97kCIQD/+wCulBExgOhr3mHmX43fUdqTFOVdE26RbZ7BOaZMrQIhAL7+bO/EP9z/ ZbS8s5fcZV6lPm0R0R3EDjU8UouUXJC3AiEAxq5YWig8rBKk00yY6gkSgdnzb6OR Xsu9Tw0pYkpPpEUCIQCLqtiU2WluPeHtMlUOx1/lv2cQMYg/gSB2s58VbS/ nrwIg K+AijxNdR6hMAcXPGr2/U0VkiuEWSSnbV0tYJwjTk5U= -----END RSA PRIVATE KEY----- -----BEGIN PUBLIC KEY----- MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAL76snni9v2GMPhTMTUASojXKJLeX8D5qmOo/z7guvIMyioQCEXf0YiLgCUsFeVy7YT1jHHoRGa1vNUUlFMuH6sCAwEAAQ == -----END PUBLIC KEY-----

Hash-based Message Authentication Codes (HMAC) Hash-based Message Authentication Codes (HMAC)

JSON Web Tokens in Detail JSON Web Token (JWT) is an open standard ( RFC 7519 ) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. JWT Format 1. Header (JOSE Header) 2. Payload Based on token signing/encryption additional information added. JWT could be JWS (Signed token) or could be JWE (Encrypted token)

JWT Header Every JWT carries a header (also known as the JOSE header) with claims about itself. These claims establish the algorithms used, whether the JWT is signed or encrypted, and in general, how to parse the rest of the JWT . Header Format: { " alg ": "HS256", " typ ": "JWT" } • HMAC using SHA-256, called HS256 in the JWA spec.

JWT Payload The payload is the element where all the interesting user data is usually added. In addition, certain claims defined in the spec may also be present. Just like the header, the payload is a JSON object . Payload Claims: { "sub": "1234567890", "name": “Java Usergroup ", "admin": true } 3 types of claims 1. Registered Claims 2. Public Claims 3. Private Claims

Registered Claims As part of JWT specification iss : from the word issuer. A case-sensitive string or URI that uniquely identifies the party that issued the JWT sub: from the word subject. A case-sensitive string or URI that uniquely identifies the party that this JWT carries information about aud : from the word audience. Either a single case-sensitive string or URI or an array of such values that uniquely identify the intended recipients of this JWT exp: from the word expiration (time). A number representing a specific date and time in the format “seconds since epoch” as defined by POSIX nbf : from not before (time). The opposite of the exp claim. A number representing a specific date and time in the format “seconds since epoch” as defined by POSIX iat : from issued at (time). A number representing a specific date and time (in the same format as exp and nbf ) at which this JWT was issued jti : from JWT ID. A string representing a unique identifier for this JWT. This claim may be used to differentiate

Public Claims Registered with IANA

JSON Web Signature Tokens Compact Serialization Format For HMAC-based signing algorithms HS256 const encodedHeader = base64(utf8( JSON.stringify ( header ))); const encodedPayload = base64(utf8( JSON.stringify ( payload ))); const signature = base64( hmac (`${ encodedHeader }.${ encodedPayload }`, secret , sha256 )); const jwt = `${ encodedHeader } . ${ encodedPayload } . ${ signature }`; For public-key signing algorithms RS256 : const signature = base64( rsassa (`${ encodedHeader }.${ encodedPayload }`, privateKey , sha256 )); const jwt = `${ encodedHeader }.${ encodedPayload }.${ signature }`;

Java Code to generate and verify HS256 JWS Token – Nimbus JWT Java Library // Generate random 256-bit (32-byte) shared secret SecureRandom random = new SecureRandom (); byte[] sharedSecret = new byte[32]; random.nextBytes ( sharedSecret ); // Create HMAC signer JWSSigner signer = new MACSigner ( sharedSecret ); // Prepare JWT with claims set JWTClaimsSet claimsSet = new JWTClaimsSet.Builder () .subject (“ userId ") .issuer("https ://bangalore-java-usergroup.com ") . expirationTime (new Date(new Date(). getTime () + 60 * 1000)) .build(); SignedJWT signedJWT = new SignedJWT (new JWSHeader ( JWSAlgorithm.HS256 ), claimsSet ); // Apply the HMAC protection signedJWT .sign ( signer ); // Serialize to compact form, produces something like eyJhbGciOiJIUzI1NiJ9.SGVsbG8sIHdvcmxkIQ.onO9Ihudz3WkiauDO2Uhyuz0Y18UASXlSc1eS0NkWyA String jwsToken = signedJWT.serialize ();

Verify JWS HS256 Token // On the consumer side, parse the JWS and verify its HMAC signedJWT = SignedJWT.parse ( receivedJWSToken ); JWSVerifier verifier = new MACVerifier ( sharedSecret ); assertTrue ( signedJWT.verify ( verifier )); // Retrieve / verify the JWT claims according to the app requirements assertEquals (" userId ", signedJWT.getJWTClaimsSet (). getSubject ()); assertEquals (" https://bangalore-java-usergroup.com ", signedJWT.getJWTClaimsSet (). getIssuer ()); assertTrue (new Date().before( signedJWT.getJWTClaimsSet (). getExpirationTime ()));

JWS RS256 Token Generation and Verification // RSA signatures require a public and private RSA key pair, the public key // must be made known to the JWS recipient in order to verify the signatures RSAKey rsaPrivateJWK = new RSAKeyGenerator (2048) . keyID ("123").generate(); RSAKey rsaPublicJWK = rsaPrivateJWK .toPublicJWK (); // Create RSA-signer with the private key JWSSigner signer = new RSASSASigner ( rsaPrivateJWK ); SignedJWT signedJWT = new SignedJWT ( new JWSHeader.Builder ( JWSAlgorithm.RS256 ) . keyID ( rsaPrivateJWK.getKeyID ()).build (), claimsSet ); String jwsRS256Token = signedJWT.serialize (); // Verification // On the consumer side, parse the JWS and verify its RSA signature signedJWT = SignedJWT.parse (receivedJwsRS256Token); JWSVerifier verifier = new RSASSAVerifier ( rsaPublicJWK ); assertTrue ( signedJWT.verify (verifier));

JSON Web Encryption Token Structure of an Encrypted JWT In contrast to signed and unsecured JWTs, encrypted JWTs have a different compact representation JWE Compact Serialization has five elements . these elements are separated by dots , and the data contained in them is Base64-encoded. The five elements of the compact representation are, in order: 1. The protected header: a header analogous to the JWS header. 2. The encrypted key: a symmetric key used to encrypt the ciphertext and other encrypted data . This key is derived from the actual encryption key specified by the user and thus is encrypted by it. 3 . The initialization vector: some encryption algorithms require additional (usually random) data . 4. The encrypted data ( ciphertext ): the actual data that is being encrypted. 5. The authentication tag: additional data produced by the algorithms that can be used to validate the contents of the ciphertext against tampering.

JWE Token Encryption using shared secret key // Create the header JWEHeader header = new JWEHeader ( JWEAlgorithm.DIR , EncryptionMethod. A128GCM ); // Set the plain text Payload payload = new Payload (“{name:”java user group”}"); // Create the JWE object and encrypt it JWEObject jweObject = new JWEObject ( header , payload ); jweObject.encrypt (new DirectEncrypter ( sharedSecretKey )); // Serialise to compact JOSE form... String jweString = jweObject.serialize (); // Verification jweObject = JWEObject.parse ( jweString ); // Decrypt jweObject.decrypt (new DirectDecrypter ( sharedSecretKey ); // Get the plain text payload = jweObject.getPayload ();

OpenId Connect use case

spring: security: oauth2: client: provider: google : jwk -set- uri : https://www.googleapis.com/oauth2/v3/certs token- uri : https://www.googleapis.com/oauth2/v4/token user-name-attribute: profile user-info- uri : https://www.googleapis.com/oauth2/v3/userinfo authorization- uri : https://accounts.google.com/o/oauth2/v2/auth registration: google : client-secret: << google provided client secret>> authorization-grant-type: authorization_code redirect- uri : https://meetup.com/login/oauth2/code/google client-id: << google provided client Id>> client-name: Google scope: profile email Spring BOOT – Spring Security Properties

Resources https://cheatsheetseries.owasp.org/cheatsheets/JSON_Web_Token_for_Java_Cheat_Sheet.html https://datatracker.ietf.org/doc/rfc8725/ JSON Web Token Best Current Practices https://connect2id.com/products/nimbus-jose-jwt/examples Nimbus jwt library examples. https://jwt.io/ download JWT Hand Book