73 lines
1.4 KiB
Plaintext
73 lines
1.4 KiB
Plaintext
== How to fix it in Java JWT
|
|
|
|
=== Code examples
|
|
|
|
include::../../common/fix/code-rationale.adoc[]
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,java,diff-id=11,diff-type=noncompliant]
|
|
----
|
|
import io.jsonwebtoken.Jwts;
|
|
|
|
public void encode() {
|
|
Jwts.builder()
|
|
.setSubject(USER_LOGIN)
|
|
.compact(); // Noncompliant
|
|
}
|
|
----
|
|
|
|
[source,java,diff-id=12,diff-type=noncompliant]
|
|
----
|
|
import io.jsonwebtoken.Jwts;
|
|
|
|
public void decode() {
|
|
Jwts.parser()
|
|
.setSigningKey(SECRET_KEY)
|
|
.parse(token)
|
|
.getBody(); // Noncompliant
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java,diff-id=11,diff-type=compliant]
|
|
----
|
|
import io.jsonwebtoken.Jwts;
|
|
|
|
public void encode() {
|
|
Jwts.builder()
|
|
.setSubject(USER_LOGIN)
|
|
.signWith(SignatureAlgorithm.HS256, SECRET_KEY)
|
|
.compact();
|
|
}
|
|
----
|
|
|
|
When using `Jwts.parser()`, make sure to call `parseClaimsJws` instead of `parse`
|
|
as it throws exceptions for invalid or missing signatures.
|
|
|
|
[source,java,diff-id=12,diff-type=compliant]
|
|
----
|
|
import io.jsonwebtoken.Jwts;
|
|
|
|
public void decode() {
|
|
Jwts.parser()
|
|
.setSigningKey(SECRET_KEY)
|
|
.parseClaimsJws(token)
|
|
.getBody();
|
|
}
|
|
----
|
|
|
|
=== How does this work?
|
|
|
|
include::../../common/fix/encode.adoc[]
|
|
|
|
include::../../common/fix/decode.adoc[]
|
|
|
|
=== Going the extra mile
|
|
|
|
include::../../common/extra-mile/key-storage.adoc[]
|
|
|
|
include::../../common/extra-mile/key-rotation.adoc[]
|
|
|