paseto-toolkit / jpaseto Goto Github PK
View Code? Open in Web Editor NEWA library for creating and parsing Paseto in Java
License: Apache License 2.0
A library for creating and parsing Paseto in Java
License: Apache License 2.0
Hello,
I am trying to use a custom KeyResolver
with the DefaultPasetoParserBuilder
, but I get an exception:
java.lang.IllegalArgumentException: PasetoParser must be configure with a public key (for public tokens) and/or a sharedSecret (for local tokens).
This exception is coming from line 77 of DefaultPasetoParserBuilder
:
Assert.isTrue( publicKey != null || sharedSecret != null,"...");
This needs to change to this so that you can use a key resolver:
Assert.isTrue(keyResolver != null || publicKey != null || sharedSecret != null,"...");
Please let me know if there are any questions on this, as I would like it to be resolved ASAP!
We are evaluating the wonderful jpaseto library for one of our project. Kindly find our observation and their respective code.
Our primary concern about the 1 minute for token creation and we can't afford this at our production (Time mentioned in Milliseconds).
Kindly check the primary testing code and give your suggestion if any improvements.
Our Testing System Configuration :
system HP ProBook 440 G6
processor Intel(R) Core(TM) i7-8565U CPU @ 1.80GH
memory 8GiB SODIMM DDR4 Synchronous 3200 MHz
memory 256KiB L1 cache
memory 1MiB L2 cache
`public class JPasetoExample {
private static final SecretKey SHARED_SECRET = Keys.secretKey();
public static void main(String[] args) {
System.out.print("Secret Key in Base64 -- " + Base64.getEncoder().encodeToString(SHARED_SECRET.getEncoded())+"\n");
long start = System.currentTimeMillis();
String tokenString = createToken();
long end = System.currentTimeMillis();
log(" Token Creation Time -- " + (end-start));
log("Paseto token: "+ tokenString);
start = System.currentTimeMillis();
Paseto result = parseToken(tokenString);
end = System.currentTimeMillis();
log(" Token Parse Time -- " + (end-start));
start = System.currentTimeMillis();
log("Token Claims:");
result.getClaims().forEach((key, value) -> log(" "+ key + ": " + value));
end = System.currentTimeMillis();
log(" Token Claims Traversal -- " + (end-start));
start = System.currentTimeMillis();
String audience = result.getClaims().getAudience();
log("Audience: "+ audience);
end = System.currentTimeMillis();
log(" Token get Audience -- " + (end-start));
start = System.currentTimeMillis();
int rolledValue = result.getClaims().get("1d20", Integer.class);
log("1d20 rolled: " + rolledValue);
end = System.currentTimeMillis();
log(" Token Custome Claim -- " + (end-start));
start = System.currentTimeMillis();
parseTokenWithRequirements(tokenString);
end = System.currentTimeMillis();
log(" Token Parse Time with Requirements -- " + (end-start));
}
public static String createToken() {
Instant now = Instant.now();
String token = Pasetos.V1.LOCAL.builder()
.setSharedSecret(SHARED_SECRET)
.setIssuedAt(now)
.setExpiration(now.plus(1, ChronoUnit.HOURS))
.setAudience("blog-post")
.setIssuer("https://developer.okta.com/blog/")
.claim("1d20", new Random().nextInt(20) + 1)
.compact();
return token;
}
public static Paseto parseToken(String token) {
PasetoParser parser = Pasetos.parserBuilder()
.setSharedSecret(SHARED_SECRET)
.build();
Paseto result = parser.parse(token);
return result;
}
public static Paseto parseTokenWithRequirements(String token) {
PasetoParser parser = Pasetos.parserBuilder()
.setSharedSecret(SHARED_SECRET)
.requireAudience("blog-post")
.requireIssuer("https://developer.okta.com/blog/")
.build();
Paseto result = parser.parse(token);
return result;
}
private static void log(String message) {
System.out.println(message);
}
}`
Output :
Secret Key in Base64 -- JdhPEhZ2B87HmbJ+6JOoA+uAMFnZEKqQbMOSWXdUFQo=
Token Creation Time -- 91076
Paseto token: v1.local.Dgw158XSwr7sxzFbtkXfoOIFu37_gxEUNX5D6KLwhMdCqlwQCBJaFJyMDPPpSXEhHMWxLDj49vCLzvqS-e0K4bwJpmz90WrRNpESkjP1DFoisJUu5KQpHgZ8xjsgrxLgfyQoPIBLcZ61nTpDFmb6UdLQQQmqy21_vMELM_sSpv-1Su-IUtKyvEfgwkAevIW7-vAO_AdHJ1TnFFySRzqhmRjKbpKs1qXqFBLP4l2rM9hSUDcJeZBaXqwi1OxshKlND2LEbk2SL79paaSfC-doDblbbhmGrbs3z9HoyKdKawJnwLQuXKi1
Token Parse Time -- 21
Token Claims:
aud: blog-post
1d20: 7
iss: https://developer.okta.com/blog/
exp: 2020-08-14T08:39:18.594777+00:00
iat: 2020-08-14T07:39:18.594777+00:00
Token Claims Traversal -- 1
Audience: blog-post
Token get Audience -- 0
1d20 rolled: 7
Token Custome Claim -- 0
Token Parse Time with Requirements -- 2
java.lang.ClassCastException: java.lang.String cannot be cast to dev.paseto.jpaseto.Paseto
I tried using instanceof keyword in java it did not work:
public Integer pasetoclaims(Object clientToken, String param) {
Integer result = null;
Paseto token = null;
try {
if(clientToken instanceof Paseto)
token = (Paseto) clientToken;
if (param.contains("name"))
result = token.getClaims().get("name", Integer.class);
else
result = token.getClaims().get(param, Integer.class);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
I also tried using getclass but it did not work,
public Integer pasetoclaims(Object clientToken, String param) {
Integer result = null;
Paseto token = null;
try {
if(clientToken.getClass().equals(Paseto.class)) //This is where i have used getclass
token = (Paseto) clientToken;
if (param.contains("name"))
result = token.getClaims().get("name", Integer.class);
else
result = token.getClaims().get(param, Integer.class);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
Can anyone suggest how to cast it in a proper way . Thanks in advance.
Hi,
I am working on the integration of Paseto tokens with the Micronaut Framework. I have been using JPaseto. Thanks for your library.
Are there any plans to support PASERK. For JWT, we support users exposing a /keys
endpoint with a JSON Web Key Set and the consumption of such an endpoint with a remotejwks_uri
to load the public keys.
I think it would be great to support the same with Paseto tokens. It would be great if Paserk was supported in JPaseto.
already downloaded all the dependencies but still keeps giving this exception
Exception in thread "main" dev.paseto.jpaseto.PasetoKeyException: Failed to generate Ed25519 key pair
at dev.paseto.jpaseto.lang.Keys.keyPairFor(Keys.java:60)
at com.prototype.token.GenerateToken.apply(GenerateToken.java:19)
at com.prototype.token.GenerateToken.main(GenerateToken.java:33)
Caused by: java.security.NoSuchAlgorithmException: Ed25519 KeyPairGenerator not available
at java.base/java.security.KeyPairGenerator.getInstance(KeyPairGenerator.java:236)
at dev.paseto.jpaseto.lang.Keys.keyPairFor(Keys.java:57)
... 2 more
I don't think this library is currently running tests against the PASETO Test Vectors. I maybe good to have that test coverage.
Hello!
I'm using the jpaseto maven artifact :
<dependency>
<groupId>dev.paseto</groupId>
<artifactId>jpaseto-api</artifactId>
<version>0.5.0</version>
</dependency>
And when I try to run my spring boot project with mvn spring-boot:run on my Windows / Mac / Raspberry Pi machine it works beautifully , but when I try to run inside an ubuntu server it gets stuck when I try to run the singleton I made for the jpaseto.
The class that has the singleton is the following:
package com.apala.services.security;
import com.apala.services.repositories.UserRepo;
import dev.paseto.jpaseto.PasetoException;
import dev.paseto.jpaseto.Pasetos;
import dev.paseto.jpaseto.lang.Keys;
import lombok.Data;
import lombok.ToString;
import org.springframework.beans.factory.annotation.Autowired;
import javax.crypto.SecretKey;
import java.util.Base64;
@Data
@ToString
public class Security {
/**
* Secret key that generates all tokens
*/
private SecretKey secretKey;
private static Security security = null;
public static Security getInstance(){
if (security == null)
security = new Security();
return security;
}
/**
* Generate a new security key
*/
private Security(){
this.secretKey=Keys.secretKey();
}
/**
* @param phoneNumber of the user we want to generate the token
* @return paseto token valid for the user
*/
public String generateTokenForPhoneNumber(int phoneNumber){
return Pasetos.V1.LOCAL.builder()
.setSubject(Integer.toString(phoneNumber))
.setSharedSecret(this.secretKey)
.compact();
}
/**
* @param token sent from the user to get validated
* @return the phone number encrypted from the token
* @throws PasetoException if the token is not valid
*/
public int getPhoneNumberFromToken(String token) throws PasetoException {
return Integer.parseInt(Pasetos.parserBuilder().setSharedSecret(this.secretKey).build().parse(token).getClaims().getSubject());
}
/**
* Load a secret key from the string
* @param key we want to be the secret key
*/
public void loadSecretKeyFromString(String key){
this.secretKey = Keys.secretKey(key.getBytes());
System.out.println("This is the new secret key -> " + this.readSecretKey());
}
/**
* Decodes the secret key
* @return secret key in plain text
*/
public String readSecretKey(){
String base64Key = Base64.getEncoder().encodeToString(this.secretKey.getEncoded());
byte[] decodedBytes = Base64.getDecoder().decode(base64Key);
return new String(decodedBytes);
}
}
I've tried to change the JDK to almost every version inside the ubuntu cloud server and also tried to change the cloud host , always get the same result. I'm not sure why this is happening and why it works on some machines and not on ubuntu , because it does not throw any error , it just get stuck as follows the output from my ubuntu server
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.google.inject.internal.cglib.core.$ReflectUtils$1 (file:/usr/share/maven/lib/guice.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of com.google.inject.internal.cglib.core.$ReflectUtils$1
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
[INFO] Scanning for projects...
[INFO]
[INFO] -------------------------< com.apala:services >-------------------------
[INFO] Building services 0.1.0
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] >>> spring-boot-maven-plugin:2.3.4.RELEASE:run (default-cli) > test-compile @ services >>>
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ services ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ services ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) @ services ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /home/apala/apala/services/src/test/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ services ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] <<< spring-boot-maven-plugin:2.3.4.RELEASE:run (default-cli) < test-compile @ services <<<
[INFO]
[INFO]
[INFO] --- spring-boot-maven-plugin:2.3.4.RELEASE:run (default-cli) @ services ---
[INFO] Attaching agents: []
And my main function is the following
@SpringBootApplication
public class ServicesApplication {
public static void main(String[] args) {
// Create a security key for paseto tokens
Security.getInstance().loadSecretKeyFromString("very_very_secret_key");
SpringApplication.run(ServicesApplication.class, args);
}
}
Does someone knows what's happening? Thanks in advance!
java.lang.SecurityException: JVM does not provide a strong secure random number generator
at dev.paseto.jpaseto.impl.DefaultPasetoV1LocalBuilder.compact(DefaultPasetoV1LocalBuilder.java:61)
Caused by: java.security.NoSuchAlgorithmException: Null/empty securerandom.strongAlgorithms Security Property
at java.security.SecureRandom.getInstanceStrong(SecureRandom.java:623)
at dev.paseto.jpaseto.impl.DefaultPasetoV1LocalBuilder.compact(DefaultPasetoV1LocalBuilder.java:59)
... 132 more
Java -- Version:
java version "1.8.0_341"
Java(TM) SE Runtime Environment (build 1.8.0_341-b10)
Java HotSpot(TM) 64-Bit Server VM (build 25.311-b11, mixed mode)
Red Hat Enterprise Linux Server release 7.9 (Maipo)
haveged 1.9.13
PASETO v3/v4 have been specified. The PASETO specification now lives here: https://github.com/paseto-standard/paseto-spec
The rationale for V3/V4 is worth reviewing.
We also updated our Implementation Guide and filed issues with other libraries to make sure Algorithm Lucidity is addressed, but JPaseto already did this, so you didn't hear from us. Good job ;)
(I'm sure this is already on your radar, but we've found having an issue somewhere is helpful.)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.