How do i add custom claims to the token?
Closed this issue · 4 comments
showkoth commented
How do i add custom claims to the token?
atholbro commented
You can extend the Token class and add whatever additional fields you need.
jaycynth commented
Can I get an example of it
atholbro commented
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.
atholbro commented
Here's a repo with a full working example:
https://github.com/atholbro/paseto-example-custom-claim