Skip to content

Instantly share code, notes, and snippets.

@sandipchitale
Last active August 10, 2023 06:00
Show Gist options
  • Save sandipchitale/d6f1c5c3cc993b59693762ad933026f9 to your computer and use it in GitHub Desktop.
Save sandipchitale/d6f1c5c3cc993b59693762ad933026f9 to your computer and use it in GitHub Desktop.
Shared Secret Key #spring-authorization-server
private static String secret = UUID.randomUUID().toString();
private static SecretKey key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
private static JWKSource<SecurityContext> immutableSecret = new ImmutableSecret<SecurityContext>(key);
@Bean
public OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer() {
return context -> {
JwsHeader.Builder headers = context.getJwsHeader();
if (context.getTokenType().equals(OAuth2TokenType.ACCESS_TOKEN) || context.getTokenType().equals(OAuth2TokenType.REFRESH_TOKEN)) {
// We are using HS256 with shared secret key
headers.algorithm(MacAlgorithm.HS256);
}
};
}
@Bean
public JwtEncoder jwtEncoder() {
// Use shared secret
return new NimbusJwtEncoder(immutableSecret);
}
@Bean
public JwtDecoder jwtDecoder() {
// Use shared secret
JwtDecoder jwtDecoder = OAuth2AuthorizationServerConfiguration.jwtDecoder(immutableSecret);
if (jwtDecoder instanceof NimbusJwtDecoder nimbusJwtDecoder) {
nimbusJwtDecoder.setJwtValidator(new JwtTimestampValidator(Duration.of(0, ChronoUnit.SECONDS)));
}
return jwtDecoder;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment