Analyses JWT libraries for java platform | Статья в журнале «Техника. Технологии. Инженерия»

Отправьте статью сегодня! Журнал выйдет 11 мая, печатный экземпляр отправим 15 мая.

Опубликовать статью в журнале

Автор:

Рубрика: Спецвыпуск

Опубликовано в Техника. Технологии. Инженерия №2 (4) апрель 2017 г.

Дата публикации: 04.05.2017

Статья просмотрена: 602 раза

Библиографическое описание:

Садуллаев, Н. Д. Analyses JWT libraries for java platform / Н. Д. Садуллаев. — Текст : непосредственный // Техника. Технологии. Инженерия. — 2017. — № 2.1 (4.1). — С. 25-27. — URL: https://moluch.ru/th/8/archive/57/2337/ (дата обращения: 27.04.2024).



JWT is a compact, URL-safe means of representing claims to be transferred between two parties. JWT libraries implemented most common languages. In this article we discuss about popular JWT libraries for Java platform and we compare them each others.

Key words. JSON, JWT, JOSE Header, Claims, Claims set, Issuer, Subject, Audience, Expiration Time, JWT libraries, java-jwt, jjwt, Nimbus-jose-jwt, jose4j

JWT — это компактное, безопасное для URL средство представления требований, которые должны передаваться между двумя сторонами. В библиотеках JWT реализованы наиболее распространенные языки. В этой статье мы поговорим о популярных JWT-библиотеках для платформы Java и сравниваем их друг с другом.

Ключевые слова. JSON, JWT, заголовок JOSE, требовании, набор требовании, эмитент, предмет, устройств, время истечения, Библиотеки JWT, java-jwt, jjwt, nimbus-jose-jwt, jose4j

Introduction. JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) or encrypted.

JWTs represent a set of claims as a JSON object that is encoded in a JWS and JWE structure. This JSON object is the JWT Claims Set. The JSON object consists of zero or more name/value pairs (or members), where the names are strings and the values are arbitrary JSON values. These members are the claims represented by the JWT. This JSON object MAY contain whitespace or line breaks before or after any JSON values or structural characters.

A JWT is represented as a sequence of URL-safe parts separated by period ('.') characters. Each part contains a base64url-encoded value. The number of parts in the JWT is dependent upon the representation of the resulting JWS using the JWS Compact Serialization or JWE using the JWE Compact Serialization. Usually, JWT token consists 3 parts of information:

  1. Header
  2. Payload(included Claims)
  3. Signature

Header. For a JWT object, the members of the JSON object represented by the JOSE Header describe the cryptographic operations applied to the JWT and optionally, additional properties of the JWT. Depending upon whether the JWT is a JWS or JWE, the corresponding rules for the JOSE Header values apply.

JWT Claims. The JWT Claims Set represents a JSON object whose members are the claims conveyed by the JWT. The Claim Names within a JWT Claims Set MUST be unique; JWT parsers MUST either reject JWTs with duplicate Claim Names or use a JSON parser that returns only the lexically last duplicate member name.

The set of claims that a JWT must contain to be considered valid is context dependent and is outside the scope of this specification. Specific applications of JWTs will require implementations to understand and process some claims in particular ways. However, in the absence of such requirements, all claims that are not understood by implementations MUST be ignored.

There are three classes of JWT Claim Names: Registered Claim Names, Public Claim Names, and Private Claim Names.

Registered Claim Names. The following Claim Names are registered in the IANA «JSON Web Token Claims» registry. None of the claims defined below are intended to be mandatory to use or implement in all cases, but rather they provide a starting point for a set of useful, interoperable claims. Applications using JWTs should define which specific claims they use and when they are required or optional. All the names are short because a core goal of JWTs is for the representation to be compact. The list of registered claims given below:

«iss» (Issuer) Claim. The «iss» (issuer) claim identifies the principal that issued the JWT. The processing of this claim is generally application specific. The «iss» value is a case-sensitive string containing a StringOrURI value. Use of this claim is OPTIONAL.

«sub» (Subject) Claim. The «sub» (subject) claim identifies the principal that is the subject of the JWT. The claims in a JWT are normally statements about the subject. The subject value MUST either be scoped to be locally unique in the context of the issuer or be globally unique. The processing of this claim is generally application specific. The «sub» value is a case-sensitive string containing a StringOrURI value. Use of this claim is OPTIONAL.

«aud» (Audience) Claim. The «aud» (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the «aud» claim when this claim is present, then the JWT MUST be rejected. In the general case, the «aud» value is an array of case-sensitive strings, each containing a StringOrURI value. In the special case when the JWT has one audience, the «aud» value MAY be a single case-sensitive string containing a StringOrURI value. The interpretation of audience values is generally application specific. Use of this claim is OPTIONAL.

«exp» (Expiration Time) Claim. The «exp» (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. The processing of the «exp» claim requires that the current date/time MUST be before the expiration date/time listed in the «exp» claim. Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL.

«nbf» (Not Before) Claim. The «nbf» (not before) claim identifies the time before which the JWT MUST NOT be accepted for processing. The processing of the «nbf» claim requires that the current date/time MUST be after or equal to the not-before date/time listed in the «nbf» claim. Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL.

«iat» (Issued At) Claim. The «iat» (issued at) claim identifies the time at which the JWT was issued. This claim can be used to determine the age of the JWT. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL.

«jti» (JWT ID) Claim. The «jti» (JWT ID) claim provides a unique identifier for the JWT. The identifier value MUST be assigned in a manner that ensures that there is a negligible probability that the same value will be accidentally assigned to a different data object; if the application uses multiple issuers, collisions MUST be prevented among values produced by different issuers as well. The «jti» claim can be used to prevent the JWT from being replayed. The «jti» value is a case-sensitive string. Use of this claim is OPTIONAL.

Public Claim Names. Claim Names can be defined at will by those using JWTs. However, in order to prevent collisions, any new Claim Name should either be registered in the IANA «JSON Web Token Claims» registry or be a Public Name: a value that contains a Collision-Resistant Name. In each case, the definer of the name or value needs to take reasonable precautions to make sure they are in control of the part of the namespace they use to define the Claim Name.

Private Claim Names. Aproducer and consumer of a JWT MAY agree to use Claim Names that are Private Names: names that are not Registered Claim Names or Public Claim Names. Unlike Public Claim Names, Private Claim Names are subject to collision and should be used with caution.

Signing and Encryption Order. While syntactically the signing and encryption operations for Nested JWTs may be applied in any order, if both signing and encryption are necessary, normally producers should sign the message and then encrypt the result (thus encrypting the signature). This prevents attacks in which the signature is stripped, leaving just an encrypted message, as well as providing privacy for the signer. Furthermore, signatures over encrypted text are not considered valid in many jurisdictions.

JWT libraries for Java. JWT libraries implemented most common languages such as Java, PHP, C++, JavaScript, Haskell, Go, Scala, Ruby etc. In Java programming language, we can use 4 popular JWT library for token signing and verification:

  1. Nimbus-jose-jwt. Nimbus JOSE+JWT is an open source (Apache 2.0) Java library that implements the Javascript Object Signing and Encryption (JOSE) spec suite and the closely related JSON Web Token (JWT) spec.The library can create, examine, serialise and parse the following JOSE and JWT objects (in compact format):

– Plain (unsecured) JOSE objects.

– JSON Web Signature (JWS) objects.

– JSON Web Encryption (JWE) objects.

– JSON Web Key (JWK) objects and JSON Web Key (JWK) Sets.

– Plain, signed and encrypted JSON Web Tokens (JWTs).

  1. Java-JWT. Java JWT is a most useful Java implementation of JSON Web Tokens. Current version of java-jwt library is 3.1.0 There are available client side decoder for java-jwt library called by JWTDecode.Android.
  2. jose4j. The jose.4.j library is an open source (Apache 2.0) implementation of JWT and the JOSE specification suite. It is written in Java and relies solely on the JCA APIs for cryptography.JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. JWT is the identity token format in OpenID Connect and it is also widely used in OAuth 2.0 and many other contexts that require compact message security. Current version of this library is 0.5.5
  3. JJWT. JJWT aims to be the easiest to use and understand library for creating and verifying JSON Web Tokens (JWTs) on the JVM. JJWT is a Java implementation based on the JWT, JWS, JWE, JWK and JWA RFC specifications. The library was created by Stormpath's CTO, Les Hazlewood and is now maintained by a community of contributors.. Current version of this library is 0.6.0

Java JWT Library comparison. Above tables show JWT libraries ability of signing, verifications, Reserved claim parts like that iss, sub, aud, exp…. We also find usage of signature algorithms in this tables.

Nimbus-jose-jwt

Claims

Algorithm

 Sign

 HS256

 Verify

 HS384

 iss check

 HS512

 sub check

 RS256

 aud check

 RS384

 exp check

 RS512

 nbf check

 ES256

 iat check

 ES384

 jti check

 ES512

Java-JWT v3.1.0

Claims

Algorithm

 Sign

 HS256

 Verify

 HS384

 iss check

 HS512

 sub check

 RS256

 aud check

 RS384

 exp check

 RS512

 nbf check

 ES256

 iat check

 ES384

 jti check

 ES512

jose4j v0.5.5

Claims

Algorithm

 Sign

 HS256

 Verify

 HS384

 iss check

 HS512

 sub check

 RS256

 aud check

 RS384

 exp check

 RS512

 nbf check

 ES256

 iat check

 ES384

 jti check

 ES512

Jjwt v0.6.0

Claims

Algorithm

 Sign

 HS256

 Verify

 HS384

 iss check

 HS512

 sub check

 RS256

 aud check

 RS384

 exp check

 RS512

 nbf check

 ES256

 iat check

 ES384

 jti check

 ES512

Conclusion. As we discussed, Java has a great JSON Web Token libraries for signing and verifying tokens. We also able to put reserved, public and private claims in this token. JWT libraries allow using various signature algorithms. We can select these libraries for our requirement. If you need easiest jwt library, you can select nimbus-jose-jwt library. If you should work with Auth2 framework, you may choose jose4j library. Would you like apache license API? Lets use either jose4j or Nimbus JOSE+JWT. Is your purpose is mobile device system, I recommend you java-jwt library. All of them are free and source code available on github.com and bitbuckets.org store.

References:

  1. JWT Handbook by Sebastian Payrott
  2. Nimbus JOSE + JWT documentation
  3. RESTful Web APIs: Services for a Changing World 1st Edition, by Leonard Richardson, Mike Amundsen, Sam Ruby
  4. http://jwt.io
  5. https://stormpath.com/blog/beginners-guide-jwts-in-java
  6. https://bitbucket.org/connect2id/nimbus-jose-jwt/wiki/Home
  7. https://github.com/jwtk/jjwt
  8. https://github.com/auth0/java-jwt
  9. http://svlada.com/jwt-token-authentication-with-spring-boot/
Основные термины (генерируются автоматически): JWT, JSON, MUST, JOSE, JWE, JWS, OPTIONAL, MAY, JJWT, JWK.

Ключевые слова

предмет, JSON, JWT, Заголовок JOSE, требования, Претензии установлены, эмитент, Аудитория, Время истечения, Библиотеки JWT, Java-JWT, jjwt, Nimbus-хосе-JWT, jose4j, JOSE Header, Claims, Claims set, Issuer, Subject, Audience, Expiration Time, JWT libraries, Nimbus-jose-jwt

Похожие статьи

The implementation of elective courses in preparation for students...

In the Republic of Kazakhstan to the students profile information may include students enrolled in the

In the course of studying this discipline, students must master the skills and abilities of modern object-oriented

В качестве формата обмена данными может быть использован JSON, кроме...

Похожие статьи

The implementation of elective courses in preparation for students...

In the Republic of Kazakhstan to the students profile information may include students enrolled in the

In the course of studying this discipline, students must master the skills and abilities of modern object-oriented

В качестве формата обмена данными может быть использован JSON, кроме...

Задать вопрос