{"id":28112823,"url":"https://github.com/BastiaanJansen/jwt-java","last_synced_at":"2025-05-14T05:05:06.289Z","repository":{"id":43584354,"uuid":"343409917","full_name":"BastiaanJansen/jwt-java","owner":"BastiaanJansen","description":"JSON Web Token implementation for Java according to RFC 7519. Easily create, parse and validate JSON Web Tokens using a fluent API.","archived":false,"fork":false,"pushed_at":"2023-04-14T17:44:09.000Z","size":219,"stargazers_count":7,"open_issues_count":1,"forks_count":2,"subscribers_count":2,"default_branch":"main","last_synced_at":"2024-05-03T00:16:29.534Z","etag":null,"topics":["java","java-jwt","json-web-signature","json-web-token","jwt","jwt-authentication","jwt-token","rfc-7519"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/BastiaanJansen.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2021-03-01T12:33:04.000Z","updated_at":"2024-04-17T21:38:01.000Z","dependencies_parsed_at":"2024-01-03T01:24:13.467Z","dependency_job_id":null,"html_url":"https://github.com/BastiaanJansen/jwt-java","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BastiaanJansen%2Fjwt-java","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BastiaanJansen%2Fjwt-java/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BastiaanJansen%2Fjwt-java/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BastiaanJansen%2Fjwt-java/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/BastiaanJansen","download_url":"https://codeload.github.com/BastiaanJansen/jwt-java/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254076849,"owners_count":22010611,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["java","java-jwt","json-web-signature","json-web-token","jwt","jwt-authentication","jwt-token","rfc-7519"],"created_at":"2025-05-14T05:01:23.210Z","updated_at":"2025-05-14T05:05:06.282Z","avatar_url":"https://github.com/BastiaanJansen.png","language":"Java","readme":"# JWT-Java\n\n[![Build \u0026 Test](https://github.com/BastiaanJansen/jwt-java/actions/workflows/build.yml/badge.svg)](https://github.com/BastiaanJansen/jwt-java/actions/workflows/build.yml)\n![](https://img.shields.io/github/license/BastiaanJansen/JWT-Java)\n![](https://img.shields.io/github/issues/BastiaanJansen/JWT-Java)\n\nJSON Web Token library for Java according to [RFC 7519](https://tools.ietf.org/html/rfc7519).\n\n## Table of Contents\n\n* [What are JSON Web Tokens?](#what-are-json-web-tokens)\n    * [Header](#header)\n    * [Payload](#payload)\n    * [Signature](#signature)\n* [Features](#features)\n    * [Supported algorithms](#supported-algorithms)\n* [Installation](#installation)\n* [Usage](#usage)\n    * [Choose algorithm](#choose-algorithm)\n        * [Secrets](#secrets)\n    * [Creating JWT's](#creating-jwts)\n    * [Parsing JWT's](#parsing-jwts)\n    * [Validating JWT's](#validating-jwts)\n        * [Basic validation](#basic-validation)\n        * [Custom validation](#custom-validation)\n        * [Create your own validator](#create-your-own-validator)\n* [Sources](#sources) \n\n## What are JSON Web Tokens?\n\nJSON 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. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public / private key pair using RSA or ECDSA.\n\nJSON Web Tokens consist of three parts, which are seperated with `.`'s:\n* Header\n* Payload\n* Signature\n\nA JWT has therefore the following structure: `xxxxx.yyyyy.zzzzz`\n\n### Header\n\nThe header holds information about the JWT. It typically consists of two parts: the type of the token, which is JWT, and the signing algorithm being used, such as HMAC SHA256 or RSA. There are two registered header parameters:\n* `typ`: Type, is used by JWT applications to declare the media type of this complete JWT\n* `cty`: Content Type, is used by this specification to convey structural information about the JWT\n\n### Payload\n\nThe second part of the token is the payload, which contains the claims. Claims are statements about an entity and additional data. Reserved claims are called registered claims. There are seven registered claims:\n* `iss`: Issuer, identifies the principal that issued the JWT\n* `sub`: Subject, identifies the principal that is the subject of the JWT\n* `aud`: Audience, identifies the principal that is the audience of the JWT\n* `exp`: Expiration Time, identifies the expiration time on or after which the JWT must not be accepted for processing\n* `nbf`: Not-before, identifies the time before which the JWT must not be accepted for processing\n* `iat`: Issued At, identifies the time at which the JWT was issued\n* `jti`: JWT ID, provides a unique identifier for the JWT\n\n### Signature\n\nTo create the signature part you have to take the Base64URL encoded header, the Base64URL encoded payload, a secret, the algorithm specified in the header, and sign that.\n\n## Features\n\n* Creating JSON Web Tokens\n* Powerful JWT validation options\n* Self explanatory and easy to learn API\n* Fluent interfaces\n\n### Supported algorithms\n\n|      | SHA256             | SHA384             | SHA512             |\n|------|:------------------:|:------------------:|:------------------:|\n| HMAC | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark:\t|\n| RSA  | :heavy_check_mark:\t| :heavy_check_mark: | :heavy_check_mark:\t|\t\n\n## Installation\n\n### Maven\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003ecom.github.bastiaanjansen\u003c/groupId\u003e\n    \u003cartifactId\u003ejwt-java\u003c/artifactId\u003e\n    \u003cversion\u003e1.2.0\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\n### Gradle\n```gradle\nimplementation 'com.github.bastiaanjansen:jwt-java:1.2.0'\n```\n\n## Usage\n\n### Choose algorithm\n\nTo generate a JSON Web Token, you can use the fluent-interface builder API. But first, the builder expects an `Algorithm` instance. The `Algorithm` class has several static helper methods to create concrete `Algorithm` instances. For example, when you want to use the HMAC512 algorithm to sign your JWT's, create an `Algorithm` instance the following way:\n```java\nAlgorithm algorithm = Algorithm.HMAC512(\"secret\");\n```\n\nOr use another algorithm:\n```java\nKeyPair keyPair = // Get key pair\nAlgorithm algorithm = Algorithm.RSA512(keyPair);\n```\n\nFor a list of available algorithms: [Supported algorithms](#supported-algorithms)\n\n#### Secrets\n\n##### HMAC-SHA\n* `HS256` secret key must be at least 256 bits (or 32 bytes) long\n* `HS384` secret key must be at least 384 bits (or 48 bytes) long\n* `HS512` secret key must be at least 512 bits (or 64 bytes) long\n\n##### RSA\nAll RSA algorithms require a secret which is at least 2048 bits (or 256 bytes) long.\n\n### Creating JWT's\n\nWhen you have chosen an algorithm, you can use the JWT Builder to define how the JWT must look like and sign the token:\n```java\n\ntry {\n  String jwt = new JWT.Builder(algorithm)\n    .withIssuer(\"issuer\")\n    .withAudience(\"aud1\", \"aud2\")\n    .withIssuedAt(new Date())\n    .withID(\"id\")\n    .withClaim(\"username\", \"BastiaanJansen\") // add custom claims\n    .sign();\n} catch (JWTCreationException e) {\n  e.printStackTrace(); // Handle error\n}\n```\n\u003e Signed JWT's automatically have the `typ` header claim set to \"JWT\"\n\nYou can also define the header and payload before hand and add them without the JWT Builder:\n```java\nHeader header = new Header();\nheader.setAlgorithm(\"HS512\");\n\nPayload payload = new Payload();\npayload.setIssuer(\"issuer\");\npayload.setAudience(\"aud1\", \"aud2\");\npayload.setIssuedAt(new Date());\npayload.setID(\"id\");\npayload.addClaim(\"username\", \"BastiaanJansen\"); // add custom claims\n\ntry {\n  String jwt = new JWT(algorithm, header, payload).sign();\n} catch (JWTCreationException e) {\n  e.printStackTrace(); // Handle error\n}\n```\n\nThese two ways of creating JWT's will generate the same tokens.\n\nYou don't need to immediately sign your JWT. You can also just build a `JWT` instance. With a `JWT` instance, you can get the header, payload, algorithm and validate the token which will be covered in a later chapter. You can, for example, pass around this `JWT` instance to other objects without passing around `String` objects.\n\n```java\n// Build JWT instance\nJWT jwt = new JWT.Builder(algorithm)\n  .withIssuer(\"issuer\")\n  .build();\n  \nHeader header = jwt.getHeader();\nPayload payload = jwt.getPayload();\nAlgorithm algorithm = jwt.getAlgorithm();\n\ntry {\n  // To finally sign and get JWT String\n  String jwtString = jwt.sign();\n} catch (JWTCreationException e) {\n  e.printStackTrace(); // Handle error\n}\n```\n\n### Parsing JWT's\n\nTo parse raw JWT's, you can use the `JWT.fromRawJWT()` method which expects an `Algorithm` an a raw JWT string:\n```java\nString rawJWT = \"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJpc3N1ZXIiLCJzdWIiOiJzdWJqZWN0IiwianRpIjoiaWQiLCJhdWRpZW5jZSI6WyJhdWQxIiwiYXVkMiJdLCJ1c2VybmFtZSI6IkJhc3RpYWFuSmFuc2VuIn0.mu1sSfzaNKH1dJ-cC1bsrFEJiwZs7H0AhnFf5tR4D0062zsxpU90F3dMrSlbneTtrxVI3PGxJlCYN8kcfpJkpw\";\n\nAlgorithm algorithm = Algorithm.HMAC512(secret);\n\ntry {\n  JWT jwt = JWT.fromRawJWT(algorithm, jwt);\n} catch (JWTCreationException | JWTDecodeException e) {\n  e.printStackTrace(); // Handle error\n}\n\n```\nWhen you have retrieved the `JWT` instance, you can get data from the header and payload:\n```java\nHeader header = jwt.getHeader();\nPayload payload = jwt.getPayload();\n\n// Get data from header and payload\nString alg = header.getAlgorithm();\nString typ = header.getType();\nString cty = header.getContentType();\n\nString iss = payload.getIssuer();\nString sub = payload.getSubject();\nString jti = payload.getID();\nDate iat = payload.getIssuedAt();\nDate exp = payload.getExpirationTime();\nDate nbf = payload.getNotBefore();\nString[] audience = payload.getAudience();\n\nString customClaim = payload.getClaim(\"username\", String.class);\n\nboolean hasClaim = payload.containsClaim(\"key\");\n```\n\n### Validating JWT's\n\n#### Basic validation\n\nTo validate a JWT, you can use a `JWTValidator`. To validate a token in it's most basic form, use the `validate()` method on a `JWT` instance:\n```java\nJWT jwt = JWT.fromRawJWT(algorithm, \"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJpc3N1ZXIiLCJzdWIiOiJzdWJqZWN0IiwianRpIjoiaWQiLCJhdWRpZW5jZSI6WyJhdWQxIiwiYXVkMiJdLCJ1c2VybmFtZSI6IkJhc3RpYWFuSmFuc2VuIn0.mu1sSfzaNKH1dJ-cC1bsrFEJiwZs7H0AhnFf5tR4D0062zsxpU90F3dMrSlbneTtrxVI3PGxJlCYN8kcfpJkpw\");\n\ntry {\n  jwt.validate();\n  \n  // JWT is valid!\n} catch (JWTValidationException e) {\n  e.printStackTrace(); // JWT is not valid, handle error\n}\n```\nThe `validate()` method uses the `DefaultJWTValidator` class underneath. Which, by default, enforces:\n* the type (typ) in header is set to \"JWT\"\n* the signature is valid\n* when set, the expiration time is not exceeded,\n* when set, the not-before time is not after or equal current time,\n\n#### Custom validation\n\nThe `DefaultJWTValidator` does also support enforcing header or payload claims. This way you can make sure that, for example, the issuer is equal to something you expect. To use this feature, use the Builder of `DefaultJWTValidator`:\n```java\n\nJWTValidator validator = new DefaultJWTValidator.Builder()\n  .withAlgorithm(\"HS512\") // Enforce the alg in the header is set to HS512\n  .withIssuer(\"issuer\")\n  .withID(\"id\")\n  .withOneOfAudience(\"aud1\", \"aud2\") // Enforce audience has \"aud1\" or \"aud2\"\n  .withClaim(\"username\", \"BastiaanJansen\") // Enforce custom claim value\n  .build();\n\ntry {\n  // Give the verifier as argument\n  jwt.validate(validator);\n  \n  // Or verify directly on the verifier\n  verifier.validate(jwt);\n  \n  // JWT is valid!\n} catch (JWTValidationException e) {\n  e.printStackTrace(); // JWT is not valid, handle error\n}\n```\n\nOr add custom validation logic:\n```java\nJWTValidator validator = new DefaultJWTValidator.Builder()\n  .withClaim(\"username\", new ClaimValidator() {\n      @Override\n      public boolean validate(Object value) {\n          return \"bastiaanjansen\".equalsIgnoreCase(String.valueOf(value));\n      }\n  })\n  .build();\n  \n// Or use a lambda\nJWTValidator validator = new DefaultJWTValidator.Builder()\n  .withClaim(\"username\", value -\u003e \"bastiaanjansen\".equalsIgnoreCase(String.valueOf(value)))\n  .build()\n```\n\n#### Create your own validator\n\nIf the `DefaultJWTValidator` doesn't meet your requirements, you can create your own validator:\n```java\n\npublic class CustomJWTValidator implements JWTValidator {\n\n  @Override\n  public void validate(JWT jwt) throws JWTValidationException {\n    // Validate JWT\n  }\n\n}\n\n```\n\nYou can use your custom validator the same way as the `DefaultJWTValidator`:\n\n```java\ntry {\n  JWTValidator customValidator = new CustomJWTValidator();\n  \n  // Give the verifier as argument\n  jwt.validate(customValidator);\n  \n  // Or verify directly on the verifier\n  customValidator.validate(jwt);\n  \n  // JWT is valid!\n} catch (JWTValidationException e) {\n  e.printStackTrace(); // JWT is not valid, handle error\n}\n```\n\n## Sources\nSources used to gather information about JSON Web Tokens:\n* [RFC 7519](https://tools.ietf.org/html/rfc7519)\n* [jwt.io](https://jwt.io/introduction)\n\n[![Stargazers repo roster for @BastiaanJansen/OTP-Java](https://reporoster.com/stars/BastiaanJansen/JWT-Java)](https://github.com/BastiaanJansen/JWT-Java/stargazers)\n","funding_links":[],"categories":["项目","安全","Projects"],"sub_categories":["安全","Security"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FBastiaanJansen%2Fjwt-java","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FBastiaanJansen%2Fjwt-java","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FBastiaanJansen%2Fjwt-java/lists"}