Convert Figma logo to code with AI

auth0 logojava-jwt

Java implementation of JSON Web Token (JWT)

5,875
921
5,875
8

Top Related Projects

10,174

Java JWT: JSON Web Token for Java and Android

JsonWebToken implementation for node.js http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html

Spring Security

Quick Overview

Java-JWT is a Java implementation for JSON Web Tokens (JWT). It provides a simple and secure way to create and verify JWTs, which are commonly used for authentication and information exchange in web applications and APIs.

Pros

  • Easy to use with a fluent API design
  • Supports various JWT algorithms (HMAC, RSA, ECDSA)
  • Regularly maintained and updated
  • Extensive documentation and examples available

Cons

  • Limited to JWT functionality only (no support for other token types)
  • Dependency on third-party libraries for some features
  • May require additional security measures for certain use cases
  • Learning curve for developers new to JWT concepts

Code Examples

Creating a JWT:

String token = JWT.create()
    .withIssuer("auth0")
    .withClaim("username", "johndoe")
    .withExpiresAt(Instant.now().plus(10, ChronoUnit.MINUTES))
    .sign(Algorithm.HMAC256("secret"));

Verifying a JWT:

try {
    JWTVerifier verifier = JWT.require(Algorithm.HMAC256("secret"))
        .withIssuer("auth0")
        .build();
    DecodedJWT jwt = verifier.verify(token);
    String username = jwt.getClaim("username").asString();
} catch (JWTVerificationException exception) {
    // Invalid signature/claims
}

Decoding a JWT without verification:

DecodedJWT jwt = JWT.decode(token);
String issuer = jwt.getIssuer();
String username = jwt.getClaim("username").asString();

Getting Started

  1. Add the dependency to your project:

    For Maven:

    <dependency>
      <groupId>com.auth0</groupId>
      <artifactId>java-jwt</artifactId>
      <version>4.3.0</version>
    </dependency>
    

    For Gradle:

    implementation 'com.auth0:java-jwt:4.3.0'
    
  2. Import the necessary classes:

    import com.auth0.jwt.JWT;
    import com.auth0.jwt.algorithms.Algorithm;
    import com.auth0.jwt.exceptions.JWTVerificationException;
    import com.auth0.jwt.interfaces.DecodedJWT;
    import com.auth0.jwt.interfaces.JWTVerifier;
    
  3. Create and verify JWTs using the examples provided above.

Competitor Comparisons

10,174

Java JWT: JSON Web Token for Java and Android

Pros of jjwt

  • More comprehensive and feature-rich library
  • Better documentation and examples
  • Active community and frequent updates

Cons of jjwt

  • Larger dependency size
  • Steeper learning curve for beginners

Code Comparison

java-jwt:

String token = JWT.create()
    .withIssuer("auth0")
    .withClaim("name", "John Doe")
    .sign(algorithm);

jjwt:

String token = Jwts.builder()
    .setIssuer("auth0")
    .claim("name", "John Doe")
    .signWith(SignatureAlgorithm.HS256, key)
    .compact();

Key Differences

  1. API Design: jjwt offers a more fluent and intuitive API, while java-jwt has a simpler, more straightforward approach.

  2. Flexibility: jjwt provides more customization options and supports a wider range of JWT features.

  3. Performance: java-jwt is generally lighter and may have better performance for simple use cases.

  4. Ecosystem: jjwt has a larger ecosystem with additional modules for specific use cases.

  5. Learning Curve: java-jwt is easier to get started with, while jjwt requires more time to master its extensive features.

Both libraries are widely used and maintained, so the choice between them often depends on specific project requirements and developer preferences.

JsonWebToken implementation for node.js http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html

Pros of node-jsonwebtoken

  • Lightweight and easy to use in Node.js environments
  • Extensive documentation and community support
  • Supports asynchronous operations for better performance in Node.js

Cons of node-jsonwebtoken

  • Limited to JavaScript/Node.js ecosystems
  • May require additional setup for use in browser environments

Code Comparison

node-jsonwebtoken:

const jwt = require('jsonwebtoken');
const token = jwt.sign({ foo: 'bar' }, 'secret', { expiresIn: '1h' });

java-jwt:

Algorithm algorithm = Algorithm.HMAC256("secret");
String token = JWT.create()
    .withClaim("foo", "bar")
    .withExpiresAt(new Date(System.currentTimeMillis() + 3600000))
    .sign(algorithm);

Key Differences

  • Language: node-jsonwebtoken is for JavaScript/Node.js, while java-jwt is for Java
  • Ecosystem: node-jsonwebtoken integrates seamlessly with Node.js projects, while java-jwt is better suited for Java applications
  • Syntax: node-jsonwebtoken uses a more concise syntax, while java-jwt employs a builder pattern
  • Performance: node-jsonwebtoken may have better performance in Node.js environments due to its asynchronous capabilities

Both libraries are maintained by Auth0 and provide similar functionality for JWT handling in their respective ecosystems. The choice between them largely depends on the programming language and environment of your project.

Spring Security

Pros of Spring Security

  • Comprehensive security framework for Spring applications
  • Extensive authentication and authorization features
  • Large community and extensive documentation

Cons of Spring Security

  • Steeper learning curve due to complexity
  • Can be overkill for simple JWT-only requirements
  • More configuration and setup required

Code Comparison

Spring Security (JWT configuration):

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .addFilterAfter(new JWTAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class)
            .authorizeRequests()
            .antMatchers(HttpMethod.POST, "/token").permitAll()
            .anyRequest().authenticated();
    }
}

java-jwt (JWT creation):

String token = JWT.create()
    .withIssuer("auth0")
    .withClaim("username", "john.doe")
    .sign(Algorithm.HMAC256("secret"));

Spring Security offers a more comprehensive security solution with extensive features, while java-jwt focuses specifically on JWT handling. Spring Security requires more setup but provides a robust framework for complex applications. java-jwt is simpler to use for basic JWT operations but lacks the broader security features of Spring Security.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Note As part of our ongoing commitment to best security practices, we have rotated the signing keys used to sign previous releases of this SDK. As a result, new patch builds have been released using the new signing key. Please upgrade at your earliest convenience.

While this change won't affect most developers, if you have implemented a dependency signature validation step in your build process, you may notice a warning that past releases can't be verified. This is expected, and a result of the key rotation process. Updating to the latest version will resolve this for you.

A Java implementation of JSON Web Token (JWT) - RFC 7519.

Build Status Coverage Status License Maven Central javadoc

:books: Documentation - :rocket: Getting Started - :computer: API Reference :speech_balloon: Feedback

Documentation

  • Examples - code samples for common java-jwt scenarios.
  • Docs site - explore our docs site and learn more about Auth0.

Getting Started

Requirements

This library is supported for Java LTS versions 8, 11, and 17. For issues on non-LTS versions above 8, consideration will be given on a case-by-case basis.

java-jwt is intended for server-side JVM applications. Android applications should use JWTDecode.Android.

java-jwt supports the following algorithms for both signing and verification:

JWSAlgorithmDescription
HS256HMAC256HMAC with SHA-256
HS384HMAC384HMAC with SHA-384
HS512HMAC512HMAC with SHA-512
RS256RSA256RSASSA-PKCS1-v1_5 with SHA-256
RS384RSA384RSASSA-PKCS1-v1_5 with SHA-384
RS512RSA512RSASSA-PKCS1-v1_5 with SHA-512
ES256ECDSA256ECDSA with curve P-256 and SHA-256
ES384ECDSA384ECDSA with curve P-384 and SHA-384
ES512ECDSA512ECDSA with curve P-521 and SHA-512

Note - Support for ECDSA with curve secp256k1 and SHA-256 (ES256K) has been dropped since it has been disabled in Java 15

:warning: Important security note: JVM has a critical vulnerability for ECDSA Algorithms - CVE-2022-21449. Please review the details of the vulnerability and update your environment.

Installation

Add the dependency via Maven:

<dependency>
  <groupId>com.auth0</groupId>
  <artifactId>java-jwt</artifactId>
  <version>4.4.0</version>
</dependency>

or Gradle:

implementation 'com.auth0:java-jwt:4.4.0'

Create a JWT

Use JWT.create(), configure the claims, and then call sign(algorithm) to sign the JWT.

The example below demonstrates this using the RS256 signing algorithm:

try {
    Algorithm algorithm = Algorithm.RSA256(rsaPublicKey, rsaPrivateKey);
    String token = JWT.create()
        .withIssuer("auth0")
        .sign(algorithm);
} catch (JWTCreationException exception){
    // Invalid Signing configuration / Couldn't convert Claims.
}

Verify a JWT

Create a JWTVerifier passing the Algorithm, and specify any required claim values.

The following example uses RS256 to verify the JWT.

String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJpc3MiOiJhdXRoMCJ9.AbIJTDMFc7yUa5MhvcP03nJPyCPzZtQcGEp-zWfOkEE";
DecodedJWT decodedJWT;
try {
    Algorithm algorithm = Algorithm.RSA256(rsaPublicKey, rsaPrivateKey);
    JWTVerifier verifier = JWT.require(algorithm)
        // specify any specific claim validations
        .withIssuer("auth0")
        // reusable verifier instance
        .build();
        
    decodedJWT = verifier.verify(token);
} catch (JWTVerificationException exception){
    // Invalid signature/claims
}

If the token has an invalid signature or the Claim requirement is not met, a JWTVerificationException will be thrown.

See the examples and JavaDocs for additional documentation.

API Reference

Feedback

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please see the following:

Raise an issue

To provide feedback or report a bug, please raise an issue on our issue tracker.

Vulnerability Reporting

Please do not report security vulnerabilities on the public Github issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.


Auth0 Logo

Auth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout Why Auth0?

This project is licensed under the MIT license. See the LICENSE file for more info.