liveBook · Manning

JSON Web Key

As explained in Spring in Action, Sixth Edition

A JSON Web Key is a JSON representation of a cryptographic key used for signing, verification, encryption, or decryption.

A JSON Web Key (JWK) represents a cryptographic key as JSON. In an OAuth 2 authorization server, a JWK supplies the signing key for JWT tokens: the server signs with a private key, and a resource server can obtain the public key to verify a token. section 8.2

For a Spring authorization server, generate a 2048-bit RSA key pair, wrap its keys in an RSAKey, and place it in a JWKSet. Expose that set through a JWKSource bean so the server can select the key when producing tokens. section 8.2

@Bean
  public JWKSource<SecurityContext> jwkSource() 
          throws NoSuchAlgorithmException {
    RSAKey rsaKey = generateRsa();
    JWKSet jwkSet = new JWKSet(rsaKey);
    return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
  }
  
  private static RSAKey generateRsa() throws NoSuchAlgorithmException {
    KeyPair keyPair = generateRsaKey();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    return new RSAKey.Builder(publicKey)
        .privateKey(privateKey)
        .keyID(UUID.randomUUID().toString())
        .build();
  }
  
  private static KeyPair generateRsaKey() throws NoSuchAlgorithmException {
      KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
      keyPairGenerator.initialize(2048);
      return keyPairGenerator.generateKeyPair();
  }
 
  @Bean
  public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
    return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource);
  }

The configuration shows the JWKSource bean and the helper methods that generate and wrap the RSA key pair. section 8.2

How Spring in Action, Sixth Edition covers it

How deep it goes
Works through RSA key generation and JWKSource configuration; defers resource-server setup.
Examples
Shows a Spring bean that generates a 2048-bit RSA key pair and exposes it through JWKSource.
What it assumes
Assumes familiarity with Java and Spring bean configuration; introduces the signing-key role in context.
What you can do after
Build it from scratch by configuring a JWKSource for an authorization server’s JWT signing key.
How it connects
Connects JWT signatures, RSA key pairs, JWKSet, OAuth 2 authorization servers, and resource-server verification.

Also explained in

Compare how 3 books explain JSON Web Key →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring in Action, Sixth Edition. The section links point to the parts of the book it draws on.