All Projects → auth0 → Java Jwt

auth0 / Java Jwt

Licence: mit
Java implementation of JSON Web Token (JWT)

Programming Languages

java
68154 projects - #9 most used programming language

Labels

Projects that are alternatives of or similar to Java Jwt

Jwt Cracker
Simple HS256 JWT token brute force cracker
Stars: ✭ 365 (-91.89%)
Mutual labels:  jwt
Jwtdecode.swift
A library to help you decode JWTs in Swift
Stars: ✭ 384 (-91.47%)
Mutual labels:  jwt
Go Microservice Helpers
A collection of handy snippets that simplify creation of GRPC servers and clients
Stars: ✭ 400 (-91.11%)
Mutual labels:  jwt
Go Admin
基于Gin + Vue + Element UI的前后端分离权限管理系统脚手架(包含了:多租户的支持,基础用户管理功能,jwt鉴权,代码生成器,RBAC资源控制,表单构建,定时任务等)3分钟构建自己的中后台项目;文档:https://doc.go-admin.dev Demo: https://www.go-admin.dev Antd beta版本:https://preview.go-admin.dev
Stars: ✭ 5,439 (+20.84%)
Mutual labels:  jwt
Microservices Spring Boot
The source code for series of articles on Medium about Microservices with Spring Boot
Stars: ✭ 382 (-91.51%)
Mutual labels:  jwt
Vue Crud X
Vue+Express Cookbook & CRUD Component (with Vite and Web Components)
Stars: ✭ 393 (-91.27%)
Mutual labels:  jwt
Lion
使用Gradle构建,基于Java 8/11/13、SpringBoot 2.2.6.RELEASE、SpringCloud Hoxton.SR2、Spring Cloud Alibaba 2.2.0.RELEASE、MyBatis Plus 3.3.1等核心技术体系实现的一套支持云原生的分布式微服务架构,提供OAuth2/JWT权限认证、分布式事务、灰度、限流、熔断降级、分布式锁、链路追踪、MQ等功能,支持Docker容器化部署、镜像交付、K8S容器编排
Stars: ✭ 360 (-92%)
Mutual labels:  jwt
Jwtrefreshtokenbundle
Implements a Refresh Token system over Json Web Tokens in Symfony
Stars: ✭ 425 (-90.56%)
Mutual labels:  jwt
Express Rest Api Boilerplate
Express REST API with JWT Authentication and support for sqlite, mysql, and postgresql
Stars: ✭ 384 (-91.47%)
Mutual labels:  jwt
Spring Boot In Action
Spring Boot 系列实战合集
Stars: ✭ 4,153 (-7.73%)
Mutual labels:  jwt
Play Pac4j
Security library for Play framework 2 in Java and Scala: OAuth, CAS, SAML, OpenID Connect, LDAP, JWT...
Stars: ✭ 375 (-91.67%)
Mutual labels:  jwt
Jwtproxy
An HTTP-Proxy that adds AuthN through JWTs
Stars: ✭ 379 (-91.58%)
Mutual labels:  jwt
Micronaut Microservices Poc
Very simplified insurance sales system made in a microservices architecture using Micronaut
Stars: ✭ 394 (-91.25%)
Mutual labels:  jwt
Oauth2orizerecipes
OAuth2 security recipes and examples based on OAuth2orize
Stars: ✭ 367 (-91.85%)
Mutual labels:  jwt
Lua Resty Jwt
JWT For The Great Openresty
Stars: ✭ 410 (-90.89%)
Mutual labels:  jwt
His
HIS英文全称 hospital information system(医院信息系统http://59.110.234.89:9999/swagger-ui.html ),医疗信息就诊系统,系统主要功能按照数据流量、流向及处理过程分为临床诊疗、药品管理、财务管理、患者管理。诊疗活动由各工作站配合完成,并将临床信息进行整理、处理、汇总、统计、分析等。本系统包括以下工作站:门诊医生工作站、药房医生工作站、医技医生工作站、收费员工作站、对帐员工作站、管理员工作站。需求为东软提供的云医院。
Stars: ✭ 359 (-92.02%)
Mutual labels:  jwt
Pyjwt
JSON Web Token implementation in Python
Stars: ✭ 4,060 (-9.8%)
Mutual labels:  jwt
Jwt sessions
XSS/CSRF safe JWT auth designed for SPA
Stars: ✭ 431 (-90.42%)
Mutual labels:  jwt
Express Jwt
connect/express middleware that validates a JsonWebToken (JWT) and set the req.user with the attributes
Stars: ✭ 4,099 (-8.93%)
Mutual labels:  jwt
Jwt
Go JWT signing, verifying and validating
Stars: ✭ 394 (-91.25%)
Mutual labels:  jwt

Java JWT

CircleCI Coverage Status License Javadoc

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

If you're looking for an Android version of the JWT Decoder take a look at our JWTDecode.Android library.

This library requires Java 8 or higher. The last version that supported Java 7 was 3.11.0.

Installation

The library is available on both Maven Central and Bintray, and the Javadoc is published here.

Maven

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

Gradle

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

Available Algorithms

The library implements JWT Verification and Signing using the following algorithms:

JWS Algorithm Description
HS256 HMAC256 HMAC with SHA-256
HS384 HMAC384 HMAC with SHA-384
HS512 HMAC512 HMAC with SHA-512
RS256 RSA256 RSASSA-PKCS1-v1_5 with SHA-256
RS384 RSA384 RSASSA-PKCS1-v1_5 with SHA-384
RS512 RSA512 RSASSA-PKCS1-v1_5 with SHA-512
ES256 ECDSA256 ECDSA with curve P-256 and SHA-256
ES256K ECDSA256 ECDSA with curve secp256k1 and SHA-256
ES384 ECDSA384 ECDSA with curve P-384 and SHA-384
ES512 ECDSA512 ECDSA with curve P-521 and SHA-512

Usage

Pick the Algorithm

The Algorithm defines how a token is signed and verified. It can be instantiated with the raw value of the secret in the case of HMAC algorithms, or the key pairs or KeyProvider in the case of RSA and ECDSA algorithms. Once created, the instance is reusable for token signing and verification operations.

When using RSA or ECDSA algorithms and you just need to sign JWTs you can avoid specifying a Public Key by passing a null value. The same can be done with the Private Key when you just need to verify JWTs.

Using static secrets or keys:

//HMAC
Algorithm algorithmHS = Algorithm.HMAC256("secret");

//RSA
RSAPublicKey publicKey = //Get the key instance
RSAPrivateKey privateKey = //Get the key instance
Algorithm algorithmRS = Algorithm.RSA256(publicKey, privateKey);

Note: How you obtain or read keys is not in the scope of this library. For an example of how you might implement this, see this gist.

HMAC Key Length and Security

When using a Hash-based Message Authenticaton Code, e.g. HS256 or HS512, in order to comply with the strict requirements of the JSON Web Algorithms (JWA) specification (RFC7518), you must use a secret key which has the same (or larger) bit length as the size of the output hash. This is to avoid weakening the security strength of the authentication code (see NIST recomendations NIST SP 800-117). For example, when using HMAC256, the secret key length must be a minimum of 256 bits.

Using a KeyProvider:

By using a KeyProvider you can change in runtime the key used either to verify the token signature or to sign a new token for RSA or ECDSA algorithms. This is achieved by implementing either RSAKeyProvider or ECDSAKeyProvider methods:

  • getPublicKeyById(String kid): Its called during token signature verification and it should return the key used to verify the token. If key rotation is being used, e.g. JWK it can fetch the correct rotation key using the id. (Or just return the same key all the time).
  • getPrivateKey(): Its called during token signing and it should return the key that will be used to sign the JWT.
  • getPrivateKeyId(): Its called during token signing and it should return the id of the key that identifies the one returned by getPrivateKey(). This value is preferred over the one set in the JWTCreator.Builder#withKeyId(String) method. If you don't need to set a kid value avoid instantiating an Algorithm using a KeyProvider.

The following example shows how this would work with JwkStore, an imaginary JWK Set implementation. For simple key rotation using JWKS, try the jwks-rsa-java library.

final JwkStore jwkStore = new JwkStore("{JWKS_FILE_HOST}");
final RSAPrivateKey privateKey = //Get the key instance
final String privateKeyId = //Create an Id for the above key

RSAKeyProvider keyProvider = new RSAKeyProvider() {
    @Override
    public RSAPublicKey getPublicKeyById(String kid) {
        //Received 'kid' value might be null if it wasn't defined in the Token's header
        RSAPublicKey publicKey = jwkStore.get(kid);
        return (RSAPublicKey) publicKey;
    }

    @Override
    public RSAPrivateKey getPrivateKey() {
        return privateKey;
    }

    @Override
    public String getPrivateKeyId() {
        return privateKeyId;
    }
};

Algorithm algorithm = Algorithm.RSA256(keyProvider);
//Use the Algorithm to create and verify JWTs.

Create and Sign a Token

You'll first need to create a JWTCreator instance by calling JWT.create(). Use the builder to define the custom Claims your token needs to have. Finally to get the String token call sign() and pass the Algorithm instance.

  • Example using HS256

    try {
        Algorithm algorithm = Algorithm.HMAC256("secret");
        String token = JWT.create()
            .withIssuer("auth0")
            .sign(algorithm);
    } catch (JWTCreationException exception){
        //Invalid Signing configuration / Couldn't convert Claims.
    }
  • Example using RS256

    RSAPublicKey publicKey = //Get the key instance
    RSAPrivateKey privateKey = //Get the key instance
    try {
        Algorithm algorithm = Algorithm.RSA256(publicKey, privateKey);
        String token = JWT.create()
            .withIssuer("auth0")
            .sign(algorithm);
    } catch (JWTCreationException exception){
        //Invalid Signing configuration / Couldn't convert Claims.
    }

If a Claim couldn't be converted to JSON or the Key used in the signing process was invalid a JWTCreationException will raise.

Verify a Token

You'll first need to create a JWTVerifier instance by calling JWT.require() and passing the Algorithm instance. If you require the token to have specific Claim values, use the builder to define them. The instance returned by the method build() is reusable, so you can define it once and use it to verify different tokens. Finally call verifier.verify() passing the token.

  • Example using HS256

    String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJpc3MiOiJhdXRoMCJ9.AbIJTDMFc7yUa5MhvcP03nJPyCPzZtQcGEp-zWfOkEE";
    try {
        Algorithm algorithm = Algorithm.HMAC256("secret");
        JWTVerifier verifier = JWT.require(algorithm)
            .withIssuer("auth0")
            .build(); //Reusable verifier instance
        DecodedJWT jwt = verifier.verify(token);
    } catch (JWTVerificationException exception){
        //Invalid signature/claims
    }
  • Example using RS256

    String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJpc3MiOiJhdXRoMCJ9.AbIJTDMFc7yUa5MhvcP03nJPyCPzZtQcGEp-zWfOkEE";
    RSAPublicKey publicKey = //Get the key instance
    RSAPrivateKey privateKey = //Get the key instance
    try {
        Algorithm algorithm = Algorithm.RSA256(publicKey, privateKey);
        JWTVerifier verifier = JWT.require(algorithm)
            .withIssuer("auth0")
            .build(); //Reusable verifier instance
        DecodedJWT jwt = 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 raise.

Time Validation

The JWT token may include DateNumber fields that can be used to validate that:

  • The token was issued in a past date "iat" < TODAY
  • The token hasn't expired yet "exp" > TODAY and
  • The token can already be used. "nbf" < TODAY

When verifying a token the time validation occurs automatically, resulting in a JWTVerificationException being throw when the values are invalid. If any of the previous fields are missing they won't be considered in this validation.

To specify a leeway window in which the Token should still be considered valid, use the acceptLeeway() method in the JWTVerifier builder and pass a positive seconds value. This applies to every item listed above.

JWTVerifier verifier = JWT.require(algorithm)
    .acceptLeeway(1) // 1 sec for nbf, iat and exp
    .build();

You can also specify a custom value for a given Date claim and override the default one for only that claim.

JWTVerifier verifier = JWT.require(algorithm)
    .acceptLeeway(1)   //1 sec for nbf and iat
    .acceptExpiresAt(5)   //5 secs for exp
    .build();

If you need to test this behaviour in your lib/app cast the Verification instance to a BaseVerification to gain visibility of the verification.build() method that accepts a custom Clock. e.g.:

BaseVerification verification = (BaseVerification) JWT.require(algorithm)
    .acceptLeeway(1)
    .acceptExpiresAt(5);
Clock clock = new CustomClock(); //Must implement Clock interface
JWTVerifier verifier = verification.build(clock);

Decode a Token

String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJpc3MiOiJhdXRoMCJ9.AbIJTDMFc7yUa5MhvcP03nJPyCPzZtQcGEp-zWfOkEE";
try {
    DecodedJWT jwt = JWT.decode(token);
} catch (JWTDecodeException exception){
    //Invalid token
}

If the token has an invalid syntax or the header or payload are not JSONs, a JWTDecodeException will raise.

Header Claims

Algorithm ("alg")

Returns the Algorithm value or null if it's not defined in the Header.

String algorithm = jwt.getAlgorithm();

Type ("typ")

Returns the Type value or null if it's not defined in the Header.

String type = jwt.getType();

Content Type ("cty")

Returns the Content Type value or null if it's not defined in the Header.

String contentType = jwt.getContentType();

Key Id ("kid")

Returns the Key Id value or null if it's not defined in the Header.

String keyId = jwt.getKeyId();

Private Claims

Additional Claims defined in the token's Header can be obtained by calling getHeaderClaim() and passing the Claim name. A Claim will always be returned, even if it can't be found. You can check if a Claim's value is null by calling claim.isNull().

Claim claim = jwt.getHeaderClaim("owner");

When creating a Token with the JWT.create() you can specify header Claims by calling withHeader() and passing both the map of claims.

Map<String, Object> headerClaims = new HashMap();
headerClaims.put("owner", "auth0");
String token = JWT.create()
        .withHeader(headerClaims)
        .sign(algorithm);

The alg and typ values will always be included in the Header after the signing process.

Payload Claims

Issuer ("iss")

Returns the Issuer value or null if it's not defined in the Payload.

String issuer = jwt.getIssuer();

Subject ("sub")

Returns the Subject value or null if it's not defined in the Payload.

String subject = jwt.getSubject();

Audience ("aud")

Returns the Audience value or null if it's not defined in the Payload.

List<String> audience = jwt.getAudience();

Expiration Time ("exp")

Returns the Expiration Time value or null if it's not defined in the Payload.

Date expiresAt = jwt.getExpiresAt();

Not Before ("nbf")

Returns the Not Before value or null if it's not defined in the Payload.

Date notBefore = jwt.getNotBefore();

Issued At ("iat")

Returns the Issued At value or null if it's not defined in the Payload.

Date issuedAt = jwt.getIssuedAt();

JWT ID ("jti")

Returns the JWT ID value or null if it's not defined in the Payload.

String id = jwt.getId();

Private Claims

Additional Claims defined in the token's Payload can be obtained by calling getClaims() or getClaim() and passing the Claim name. A Claim will always be returned, even if it can't be found. You can check if a Claim's value is null by calling claim.isNull().

Map<String, Claim> claims = jwt.getClaims();    //Key is the Claim name
Claim claim = claims.get("isAdmin");

or

Claim claim = jwt.getClaim("isAdmin");

When creating a Token with the JWT.create() you can specify a custom Claim by calling withClaim() and passing both the name and the value.

String token = JWT.create()
        .withClaim("name", 123)
        .withArrayClaim("array", new Integer[]{1, 2, 3})
        .sign(algorithm);

You can also create a JWT by calling withPayload() and passing a map of claim names to values:

Map<String, Object> payloadClaims = new HashMap<>();
payloadClaims.put("@context", "https://auth0.com/");
String token = JWT.create()
        .withPayload(payloadClaims)
        .sign(algorithm);

You can also verify custom Claims on the JWT.require() by calling withClaim() and passing both the name and the required value.

JWTVerifier verifier = JWT.require(algorithm)
    .withClaim("name", 123)
    .withArrayClaim("array", 1, 2, 3)
    .build();
DecodedJWT jwt = verifier.verify("my.jwt.token");

Currently supported classes for custom JWT Claim creation and verification are: Boolean, Integer, Double, String, Date and Arrays of type String and Integer.

Claim Class

The Claim class is a wrapper for the Claim values. It allows you to get the Claim as different class types. The available helpers are:

Primitives

  • asBoolean(): Returns the Boolean value or null if it can't be converted.
  • asInt(): Returns the Integer value or null if it can't be converted.
  • asDouble(): Returns the Double value or null if it can't be converted.
  • asLong(): Returns the Long value or null if it can't be converted.
  • asString(): Returns the String value or null if it can't be converted.
  • asDate(): Returns the Date value or null if it can't be converted. This must be a NumericDate (Unix Epoch/Timestamp). Note that the JWT Standard specified that all the NumericDate values must be in seconds.

Custom Classes and Collections

To obtain a Claim as a Collection you'll need to provide the Class Type of the contents to convert from.

  • as(class): Returns the value parsed as Class Type. For collections you should use the asArray and asList methods.
  • asMap(): Returns the value parsed as Map<String, Object>.
  • asArray(class): Returns the value parsed as an Array of elements of type Class Type, or null if the value isn't a JSON Array.
  • asList(class): Returns the value parsed as a List of elements of type Class Type, or null if the value isn't a JSON Array.

If the values can't be converted to the given Class Type a JWTDecodeException will raise.

What is Auth0?

Auth0 helps you to:

  • Add authentication with multiple authentication sources, either social like Google, Facebook, Microsoft Account, LinkedIn, GitHub, Twitter, Box, Salesforce, among others, or enterprise identity systems like Windows Azure AD, Google Apps, Active Directory, ADFS or any SAML Identity Provider.
  • Add authentication through more traditional username/password databases.
  • Add support for linking different user accounts with the same user.
  • Support for generating signed Json Web Tokens to call your APIs and flow the user identity securely.
  • Analytics of how, when and where users are logging in.
  • Pull data from other sources and add it to the user profile, through JavaScript rules.

Create a free account in Auth0

  1. Go to Auth0 and click Sign Up.
  2. Use Google, GitHub or Microsoft Account to login.

Issue Reporting

If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

Author

Auth0

License

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].