dart_jwt 0.4.5

JSON Web Token (JWT) for Dart #

Introduction #

Provides an implementation of JSON Web Token standard.

Using #

Basic Usage #


To decode a JWT string

JsonWebToken jwt = new JsonWebToken.decode(jwtStr);


To validate the decoded jwt

Set<ConstraintViolation> violations = jwt.validate(new JwtClaimSetValidationContext());

If the jwt is valid this will return an empty set. Otherwise the set will contain all the things that were invalid.

This validates the signature and the claim set.

Note you can also validate as you decode

JsonWebToken jwt = new JsonWebToken.decode(jwtStr, validationContext: new JwtClaimSetValidationContext());

This will throw a ConstraintViolations object if the validation fails.

Claim Set The jwt object contains the set of claims being made. You can access them like so

JwtClaimSet claimSet = jwt.claimSet;

JwtClaimSet contains all the standard Jwt claims and validation also covers things like checking the expiry etc.

####Encoding#### Claim Set

First create a new claim set

final issuedAt = DateTime.now();
final expiry = issuedAt.add(const Duration(minutes: 3));

final claimSet = new JwtClaimSet('the issuer', 'fred user', expiry, issuedAt));

or if you need a more complex building process you can use MutableJwtClaimSet in a builder style

final claimSet = (new MutableJwtClaimSet()

Create the Jwt

To create a JWT encoded inside a Json Web Signature (JWS)

final signatureContext = new JwaSignatureContext(sharedSecret);
final jwt = new JsonWebToken.jws(claimSet, signatureContext);

Note: JWE encoded JWT is not yet implemented


Encoding is simply a matter of calling the encode method

String jwtString = jwt.encode();

Extending #

Custom Claims

The main way to extend the Jwt library is to add custom claims to the claimset. The following is an example of such a case. Basically you need to extend JwtClaimSet, add your fields, the to / from json and validation.

class ProductHostClaimSet extends JwtClaimSet {
  final String queryStringHash;
  ProductHostClaimSet(String issuer, String subject, DateTime expiry, DateTime issuedAt,
    : super(issuer, subject, expiry, issuedAt);
  ProductHostClaimSet.fromJson(Map json)
      : queryStringHash = json['qsh'],

  Map toJson() {
    return super.toJson()
  Set<ConstraintViolation> validate(ProductHostClaimSetValidationContext validationContext) {
    return super.validate(validationContext)
  Set<ConstraintViolation> _validateQsh(ProductHostClaimSetValidationContext validationContext) {
    final String expectedQsh = validationContext.qshFactory();
    return queryStringHash == expectedQsh ? new Set.identity() 
        : (new Set()..add(new ConstraintViolation(
            "Query String Hash mismatch. Expected '$expectedQsh'. Got '$queryStringHash'")));

You can then just create the Jwt in the normal manner

final jwt = new JsonWebToken.jws(claimSet, signatureContext);

Of course if you are not a fan of structure you can always add a single field which is a map containing all the extra claims.

Limitations #

Currently this supports enough of the JWT spec that was needed for a project. Specifically it only implements:

  • JWS (no JWE support).
  • HS256 for the JWS signature.

Whilst it is interoperating with a Java based implemention, a rigorous review of conformance to the spec has not been undertaken. Please file issues or PR's if you spot any issues with conformance or find bugs in general or need new features.

PR's with good tests will be looked apon favourably ;-)

Issues #

  • Validation needs work. The intention is to piggy back off a constraint validation library (similar to Java Bean Validation) but I haven't written that yet.

0.4.5 #

  • Fails parsing JWT headers without optional "typ" header parameter (2)

0.4.4 #

  • restored optionality of typ

0.4.2 #

  • changed to test package

0.4.1 #

  • widen dependency ranges

0.4.0 #

  • Abstracted out a base JwtClaimSet. Old JwtClaimSet is now renamed OpenIdJwtClaimSet (breaking)
  • Removed MutableJwtClaimSet (breaking)
  • Added MapJwtClaimSet

0.3.0 #

  • Audience is now a List (breaking)
  • MutableJwtClaimSet now deprecated

0.2.0 #

  • Improvements for RSA. Thanks to Jonas Kello for the contribution

0.1.3 #

  • Add RSA signatures. Thanks to Tais Plougmann Hansen for the contribution

0.1.2 #

  • make typ header optional and default to JWT

0.1.1 #

  • Add audience claim

0.1.0+2 #

  • Bug fix. Had dependency on sdk 1.3 without realising it. Changed sdk version in pubspec.yaml

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:

  dart_jwt: ^0.4.5

2. Install it

You can install packages from the command line:

with pub:

$ pub get

Alternatively, your editor might support pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:

import 'package:dart_jwt/dart_jwt.dart';
Awaiting analysis to complete.