У меня ошибка при создании токена jwt, закодированного в базе 64.
Вот возвращаемая ошибка:
Caused by:**
java.lang.ExceptionInInitializerError
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.lang.Class.newInstance(Class.java:442)
at io.quarkus.runner.RuntimeRunner.run(RuntimeRunner.java:142)
at io.quarkus.test.junit.QuarkusTestExtension.doJavaStart(QuarkusTestExtension.java:248)
at io.quarkus.test.junit.QuarkusTestExtension.createTestInstance(QuarkusTestExtension.java:390)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstanceFactory(ClassBasedTestDescriptor.java:285)
... 49 more
Caused by: java.lang.RuntimeException: Failed to start quarkus
at io.quarkus.runner.ApplicationImpl1.<clinit>(ApplicationImpl1.zig:413)
... 58 more
Caused by: java.lang.VerifyError: Bad type on operand stack
Exception Details:
Location:
com/ciwara/kalanSowApp/security/TokenProvider.validateToken(Ljava/lang/String;)Z @42: invokeinterface
Reason:
Type 'java/lang/Object' (current frame, stack[2]) is not assignable to 'java/lang/Throwable'
@ApplicationScoped
public class TokenProvider {
private final Logger log = LoggerFactory.getLogger(TokenProvider.class);
@Inject
private KalanSowAppConfiguration applicationConfiguration;
private static final String AUTHORITIES_KEY = "auth";
private Key key;
private long tokenValidityInMilliseconds;
private long tokenValidityInMillisecondsForRememberMe;
@PostConstruct
public void init() {
byte[] keyBytes;
String secret = applicationConfiguration.jwtConfiguration.base64Secret;
if (secret == null || secret.trim().equals("")) {
keyBytes = "".getBytes(StandardCharsets.UTF_8);
log.info("Using secret key", keyBytes);
} else {
log.info("Using a Base64-encoded JWT secret key");
keyBytes = Decoders.BASE64.decode(secret);
log.info("Using a Base64-encoded JWT secret key", keyBytes);
}
this.key = Keys.hmacShaKeyFor(keyBytes);
this.tokenValidityInMilliseconds = 1000 * applicationConfiguration.jwtConfiguration.tokenValidityInSeconds;
this.tokenValidityInMillisecondsForRememberMe = 1000
* applicationConfiguration.jwtConfiguration.tokenValidityInSecondsForRememberMe;
}
public String createToken(JwtPrincipal principal, boolean rememberMe) {
long now = (new Date()).getTime();
Date validity;
if (rememberMe) {
validity = new Date(now + this.tokenValidityInMillisecondsForRememberMe);
} else {
validity = new Date(now + this.tokenValidityInMilliseconds);
}
return Jwts.builder().setSubject(principal.getName()).claim(AUTHORITIES_KEY, principal.getAuthorities())
.signWith(this.key, SignatureAlgorithm.HS512).setExpiration(validity).compact();
}
public Principal getPrincipal(String token) {
Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
String[] roles = null;
if (claims.get(AUTHORITIES_KEY) != null) {
Collection<String> authorities = Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(","))
.collect(Collectors.toList());
roles = (String[]) authorities.toArray();
}
return new JwtPrincipal(claims.getSubject(), roles);
}
public boolean validateToken(String authToken) throws ExceptionInInitializerError {
try {
// OK, we can trust this JWT
Jwts.parser().setSigningKey(key).parseClaimsJws(authToken);
return true;
} catch (io.jsonwebtoken.security.SecurityException | MalformedJwtException e) {
// don't trust the JWT!
log.info("Invalid JWT signature.");
log.trace("Invalid JWT signature trace: {}", e);
} catch (ExpiredJwtException e) {
log.info("Expired JWT token.");
log.trace("Expired JWT token trace: {}", e);
} catch (UnsupportedJwtException e) {
log.info("Unsupported JWT token.");
log.trace("Unsupported JWT token trace: {}", e);
} catch (IllegalArgumentException e) {
log.info("JWT token compact of handler are invalid.");
log.trace("JWT token compact of handler are invalid trace: {}", e);
}
// don't trust the JWT!
return false;
}
}
Я не понимаю, где является проблемой плохого типа в проблеме стека операнда.
Класс конфигурации:
@ConfigProperties(prefix = "application")
public class KalanSowAppConfiguration {
public JwtConfiguration jwtConfiguration = new JwtConfiguration();
@ConfigProperties(prefix = "application.jwtConfiguration")
public static class JwtConfiguration {
@ConfigProperty(name = "base64-secret")
public String base64Secret;
@ConfigProperty(name = "tokenValidityInSeconds", defaultValue = "300")
public long tokenValidityInSeconds;
@ConfigProperty(name = "tokenValidityInSecondsForRememberMe", defaultValue = "7200")
public long tokenValidityInSecondsForRememberMe;
}
public JwtConfiguration getJwtConfiguration() {
return jwtConfiguration;
}
public void setJwtConfiguration(JwtConfiguration jwtConfiguration) {
this.jwtConfiguration = jwtConfiguration;
}
}
Класс конфигурации читайте файл application.properties. Файл свойств содержит секретный ключ и base64Secret для генерации токена.
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ciwara.kalanSowApp</groupId>
<artifactId>kalanSow-Backend</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<surefire-plugin.version>2.22.0</surefire-plugin.version>
<maven.compiler.parameters>true</maven.compiler.parameters>
<quarkus.version>0.26.1</quarkus.version>
<compiler-plugin.version>3.8.1</compiler-plugin.version>
<maven.compiler.source>1.8</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.target>1.8</maven.compiler.target>
<jboss-logging.version>3.3.2.Final</jboss-logging.version>
<nimbus-jose.version>8.4</nimbus-jose.version>
<mockito.version>3.2.4</mockito.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-bom</artifactId>
<version>${quarkus.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- <dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-arc</artifactId>
<scope>provided</scope>
</dependency> -->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy-jsonb</artifactId>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-rest-client</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.10.7</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.10.7</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.10.7</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>${nimbus-jose.version}</version>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
</dependency>
<!-- <dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
</dependency> -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-jdbc-postgresql</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/io.quarkus/quarkus-jdbc-h2 -->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-jdbc-h2</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/io.quarkus/quarkus-jdbc-h2 -->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-test-h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-orm-panache</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-orm</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-security</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-smallrye-openapi</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-smallrye-metrics</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-smallrye-health</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-spring-web</artifactId>
</dependency>
<!-- <dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-undertow</artifactId>
</dependency> -->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-spring-di</artifactId>
</dependency>
<!-- <dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web-client</artifactId>
</dependency> -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-maven-plugin</artifactId>
<version>${quarkus.version}</version>
<executions>
<execution>
<goals>
<goal>build</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${compiler-plugin.version}</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire-plugin.version}</version>
<configuration>
<systemProperties>
<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
</systemProperties>
</configuration>
</plugin>
<!-- <plugin>
<groupId>org.jboss.jandex</groupId>
<artifactId>jandex-maven-plugin</artifactId>
<version>1.0.7</version>
</plugin> -->
</plugins>
</build>
<profiles>
<profile>
<id>native</id>
<activation>
<property>
<name>native</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-maven-plugin</artifactId>
<version>${quarkus.version}</version>
<executions>
<execution>
<goals>
<goal>native-image</goal>
</goals>
<configuration>
<enableHttpUrlHandler>true</enableHttpUrlHandler>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${surefire-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
<configuration>
<systemProperties>
<native.image.path>${project.build.directory}/${project.build.finalName}-runner</native.image.path>
</systemProperties>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>default</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<junit.includes>**/*Test.java</junit.includes>
<junit.excludes>**/*Test.java</junit.excludes>
</properties>
</profile>
</profiles>
</project>