delphi jose jwt

2025-12-10 0 426

Delphi JOSE and JWT Library

What is Delphi JOSE and JWT Library

Delphi implementation of JWT (JSON Web Token) and the JOSE (JSON Object Signing and Encryption) specification suite. This library supports the JWS (JWE support is planned) compact serializations with several JOSE algorithms.

Articles about using Delphi-JOSE

  • JWT authentication with Delphi. Part 1 – JWT and authentication technologies introduction (using Delphi)
  • JWT authentication with Delphi. Part 2 – Understanding the JSON Web Token
  • JWT authentication with Delphi. Part 3 – Using Delphi-JOSE-JWT to generate and verify JWT tokens
  • JWT authentication with Delphi. Part 4 – Using JWT consumer to validate JWT\’s claims

️ Important: OpenSSL requirements

HMAC using SHA algorithm

Prior to Delphi 10 Seattle the the HMAC-SHA algorithm uses OpenSSL through the Indy library, so in order to generate the token you should have the OpenSSL DLLs in your server system.

In Delphi 10 Seattle or newer Delphi versions the HMAC algorithm is also in the System.Hash unit so OpenSSL is not needed.

HMAC using RSA or ECDSA algorithm

The HMAC-RSA(ECDSA) algorithm uses necessarily OpenSSL so if you plan to use these algorithms to sign your token you have to download and deploy OpenSSL (on the server).

Client-side considerations

Please keep in mind that the client doesn\’t have to generate or verify the token (using SHA or RSA) so on the client-side there\’s no need for the OpenSSL DLLs.

OpenSSL download

If you need the OpenSSL library on the server, you can download the package directly to the Indy\’s GitHub project page (keep in mind to always update to the latest version and to match you application\’s bitness)

❓ What is JOSE

JOSE is a standard that provides a general approach to the signing and encryption of any content. JOSE consists of several RFC:

  • JWT (JSON Web Token) – describes representation of claims encoded in JSON
  • JWS (JSON Web Signature) – describes producing and handling signed messages
  • JWE (JSON Web Encryption) – describes producing and handling encrypted messages
  • JWA (JSON Web Algorithms) – describes cryptographic algorithms used in JOSE
  • JWK (JSON Web Key) – describes format and handling of cryptographic keys in JOSE

⚡ General Features

Token serialization

  • One method call to serialize a token

Token deserialization

  • One method call to validate and deserialize a compact token

Token & Claims validation (Consumer)

Algorithms Supported
exp ✔️
iat ✔️
nbf ✔️
aud ✔️
iss ✔️
jti ✔️
typ ✔️

Easy to use classes for compact token productiom

  • Easy to use TJOSEProducer and TJOSEProducerBuilder (alias TJOSEProcess) classes to build a new compact token with many options

Easy to use classes for custom validation

  • Easy to use TJOSEConsumer and TJOSEConsumerBuilder classes to validate token with a fine granularity
  • Easy to write custom validators!

Signing algorithms

Algorithms Supported
None ✔️ don\’t use it! ?
HS256 ✔️
HS384 ✔️
HS512 ✔️
RS256 ✔️ updated!
RS384 ✔️ updated!
RS512 ✔️ updated!
ES256 ✔️ new! ?
ES384 ✔️ new! ?
ES512 ✔️ new! ?
ES256K ✔️ new! ?

Security notes

  • This library is not affected by the None algorithm vulnerability
  • This library is not susceptible to the recently discussed encryption vulnerability.

Projects using Delphi JOSE and JWT

  • The WiRL RESTful Library for Delphi
  • TMS XData and TMS Sparkle. Read the blog post by Wagner R. Landgraf (he is also a contributor of this project)

? Todo

Features
  • JWE support (there is partial implementation in this PR)
  • Support of other crypto libraries (TMS Cryptography Pack, etc…)
Code
  • More unit tests
  • More examples

? Prerequisite

This library has been tested with Delphi 12 Athens, Delphi 11 Alexandria, Delphi 10.4 Sydney, Delphi 10.3 Rio, Delphi 10.2 Tokyo but with some work it should compile with DXE6 and higher but I have not tried or tested this, if you succeed in this task I will be happy to create a branch of your work!

Libraries/Units dependencies

This library has no dependencies on external libraries/units.

Delphi units used:

  • System.JSON (DXE6+) (available on earlier Delphi versions as Data.DBXJSON)
  • System.Rtti (D2010+)
  • System.Generics.Collections (D2009+)
  • System.NetEncoding (DXE7+)
  • Indy units: IdHMAC, IdHMACSHA1, IdSSLOpenSSL, IdHash

Indy notes

  • Please use always the latest version from GitHub

? Installation

Manual installation

Simply add the source path \”Source/Common\” and Source/JOSE\” to your Delphi project path and.. you are good to go!

Boss package manager

Using the boss install command:

$ boss install github.com/paolo-rossi/delphi-jose-jwt

Quick Code Examples

Creating a token

To create a token, simply create an instance of the TJWT class and set the properties (claims).

Using TJOSE utility class

The easiest way to build a JWT token (compact representation) is to use the IJOSEProducer interface:

uses
  JOSE.Producer;

var
  LResult: string;
begin
  LResult := TJOSEProcess.New
    .SetIssuer(\'Delphi JOSE Library\')
    .SetIssuedAt(Now)
    .SetExpiration(Now + 1)
    .SetAlgorithm(LAlg)
    .SetKey(TJOSEAlgorithmId.HS256)
    .Build
    .GetCompactToken
  ;

  memoCompact.Lines.Add(LResult);
end;

Using TJOSE utility class

Another way to serialize, deserialize, verify a token is to use the TJOSEutility class:

uses
  JOSE.Core.JWT,
  JOSE.Core.Builder;

var
  LToken: TJWT;
  LCompactToken: string;
begin
  LToken := TJWT.Create;
  try
    // Token claims
    LToken.Claims.Issuer := \'WiRL REST Library\';
    LToken.Claims.Subject := \'Paolo Rossi\';
    LToken.Claims.Expiration := Now + 1;

    // Signing and Compact format creation
    LCompactToken := TJOSE.SHA256CompactToken(\'my_very_long_and_safe_secret_key\', LToken);
    mmoCompact.Lines.Add(LCompactToken);
  finally
    LToken.Free;
  end;

Using TJWT, TJWS and TJWK classes

Using the TJWT, TJWS and TJWK classes you have more control over the creation of the final compact token.

var
  LToken: TJWT;
  LSigner: TJWS;
  LKey: TJWK;
  LAlg: TJOSEAlgorithmId;
begin
  LToken := TJWT.Create;
  try
    // Set your claims
    LToken.Claims.Subject := \'Paolo Rossi\';
    LToken.Claims.Issuer := \'Delphi JOSE Library\';
    LToken.Claims.IssuedAt := Now;
    LToken.Claims.Expiration := Now + 1;

    // Choose the signing algorithm
    case cbbAlgorithm.ItemIndex of
      0: LAlg := TJOSEAlgorithmId.HS256;
      1: LAlg := TJOSEAlgorithmId.HS384;
      2: LAlg := TJOSEAlgorithmId.HS512;
    else LAlg := TJOSEAlgorithmId.HS256;
    end;

    // Create your key from any text or TBytes
    LKey := TJWK.Create(edtSecret.Text);

    try
      // Create the signer
      LSigner := TJWS.Create(LToken);
      try
        // With this option you can have keys < algorithm length
        LSigner.SkipKeyValidation := True;

        // Sign the token!
        LSigner.Sign(LKey, LAlg);

        memoCompact.Lines.Add(\'Header: \' + LSigner.Header);
        memoCompact.Lines.Add(\'Payload: \' + LSigner.Payload);
        memoCompact.Lines.Add(\'Signature: \' + LSigner.Signature);
        memoCompact.Lines.Add(\'Compact Token: \' + LSigner.CompactToken);
      finally
        LSigner.Free;
      end;
    finally
      LKey.Free;
    end;  
  finally
    LToken.Free;
  end;

Unpack and verify a token\’s signature

Unpacking and verifying tokens is simple.

Using TJOSE utility class

You have to pass the key and the token compact format to the TJOSE.Verify class function

var
  LKey: TJWK;
  LToken: TJWT;
begin
  // Create the key from a text or TBytes
  LKey := TJWK.Create(\'my_very_long_and_safe_secret_key\');

  // Unpack and verify the token!
  LToken := TJOSE.Verify(LKey, FCompactToken);

  if Assigned(LToken) then
  begin
    try
      if LToken.Verified then
        mmoJSON.Lines.Add(\'Token signature is verified\')
      else
        mmoJSON.Lines.Add(\'Token signature is not verified\')
    finally
      LToken.Free;
    end;
  end;

end;

Unpacking and token validation

Using the new class TJOSEConsumer it\’s very easy to validate the token\’s claims. The TJOSEConsumer object is built with the TJOSEConsumerBuilder utility class using the fluent interface.

var
  LConsumer: IJOSEConsumer;
begin
  LConsumer := TJOSEConsumerBuilder.NewConsumer
    .SetClaimsClass(TJWTClaims)

    // JWS-related validation
    .SetVerificationKey(edtConsumerSecret.Text)
    .SetSkipVerificationKeyValidation
    .SetDisableRequireSignature

    // string-based claims validation
    .SetExpectedSubject(\'paolo-rossi\')
    .SetExpectedAudience(True, [\'Paolo\'])

    // Time-related claims validation
    .SetRequireIssuedAt
    .SetRequireExpirationTime
    .SetEvaluationTime(IncSecond(FNow, 26))
    .SetAllowedClockSkew(20, TJOSETimeUnit.Seconds)
    .SetMaxFutureValidity(20, TJOSETimeUnit.Minutes)

    // Build the consumer object
    .Build();

  try
    // Process the token with your rules!
    LConsumer.Process(Compact);
  except
    // (optionally) log the errors
    on E: Exception do
      memoLog.Lines.Add(E.Message);
  end;

Paolo Rossi

下载源码

通过命令行克隆项目:

git clone https://github.com/paolo-rossi/delphi-jose-jwt.git

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

申明:本文由第三方发布,内容仅代表作者观点,与本网站无关。对本文以及其中全部或者部分内容的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。本网发布或转载文章出于传递更多信息之目的,并不意味着赞同其观点或证实其描述,也不代表本网对其真实性负责。

左子网 编程相关 delphi jose jwt https://www.zuozi.net/33691.html

NsfwBox
上一篇: NsfwBox
SynEdit
下一篇: SynEdit
常见问题
  • 1、自动:拍下后,点击(下载)链接即可下载;2、手动:拍下后,联系卖家发放即可或者联系官方找开发者发货。
查看详情
  • 1、源码默认交易周期:手动发货商品为1-3天,并且用户付款金额将会进入平台担保直到交易完成或者3-7天即可发放,如遇纠纷无限期延长收款金额直至纠纷解决或者退款!;
查看详情
  • 1、描述:源码描述(含标题)与实际源码不一致的(例:货不对板); 2、演示:有演示站时,与实际源码小于95%一致的(但描述中有”不保证完全一样、有变化的可能性”类似显著声明的除外); 3、发货:不发货可无理由退款; 4、安装:免费提供安装服务的源码但卖家不履行的; 5、收费:价格虚标,额外收取其他费用的(但描述中有显著声明或双方交易前有商定的除外); 6、其他:如质量方面的硬性常规问题BUG等。 注:经核实符合上述任一,均支持退款,但卖家予以积极解决问题则除外。
查看详情
  • 1、左子会对双方交易的过程及交易商品的快照进行永久存档,以确保交易的真实、有效、安全! 2、左子无法对如“永久包更新”、“永久技术支持”等类似交易之后的商家承诺做担保,请买家自行鉴别; 3、在源码同时有网站演示与图片演示,且站演与图演不一致时,默认按图演作为纠纷评判依据(特别声明或有商定除外); 4、在没有”无任何正当退款依据”的前提下,商品写有”一旦售出,概不支持退款”等类似的声明,视为无效声明; 5、在未拍下前,双方在QQ上所商定的交易内容,亦可成为纠纷评判依据(商定与描述冲突时,商定为准); 6、因聊天记录可作为纠纷评判依据,故双方联系时,只与对方在左子上所留的QQ、手机号沟通,以防对方不承认自我承诺。 7、虽然交易产生纠纷的几率很小,但一定要保留如聊天记录、手机短信等这样的重要信息,以防产生纠纷时便于左子介入快速处理。
查看详情

相关文章

猜你喜欢
发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务