atholbro/paseto

How do i add custom claims to the token?

Closed this issue · 4 comments

How do i add custom claims to the token?

You can extend the Token class and add whatever additional fields you need.

Can I get an example of it

Can I get an example of it

Here's the general idea.

Start by creating a custom token class which extends from Token, then add any custom claims you want with getters/setters:

public static class CustomToken extends Token {
    private String custom;

    public String getCustom() {
        return custom;
    }

    public void setCustom(String custom) {
        this.custom = custom;
    }
}

Then you can encode/decode these like so (slightly modified from the readme example):

byte[] key = decode("707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f");
TokenService<CustomToken> tokenService = PasetoBuilders.V2.localService(() -> key, CustomToken.class)
        .withDefaultValidityPeriod(Duration.ofDays(15).getSeconds())
        .build();

CustomToken token = new CustomToken();
token.setCustom("Whatever you'd like here.");
token.setTokenId("example-id"); // A session key, user id, etc.

String encoded = tokenService.encode(token);
System.out.println(encoded);

CustomToken decoded = tokenService.decode(encoded);
System.out.println(decoded.getCustom());

Basically create a custom class and use that when setting up the token service. I'll upload this as a full example project in a bit.

Here's a repo with a full working example:
https://github.com/atholbro/paseto-example-custom-claim