Table of Contents
Question content
Solution
Home Java Caught in an error. JWT validity cannot be asserted and should not be trusted

Caught in an error. JWT validity cannot be asserted and should not be trusted

Feb 15, 2024 am 09:18 AM

php editor Banana pointed out that when using JWT (JSON Web Tokens), you must note that its validity cannot be asserted and should not be trusted. JWT is a token used for authentication and authorization, but due to its self-contained nature, once the token is tampered with, its validity cannot be guaranteed. Therefore, when using JWT, we should take strict verification measures, including verifying signatures, expiration time, etc., and do not store sensitive information in JWT to avoid security risks.

Question content

My jwtutil.java code:

@service
@requiredargsconstructor
public class jwtutil {



    private secretkey getsigningkey() {
        return jwts.sig.hs512.key().build();
    }

    public string generatetoken(securitymember securitymember) {
        map<string, object> claims = new hashmap<>();
        return createtoken(claims, securitymember.getusername());
    }

    public string createtoken(map<string, object> claims, string subject) {
        return jwts.builder().claims(claims).subject(subject).issuedat(new date(system.currenttimemillis()))
                .expiration(new date(system.currenttimemillis() + 1000 * 60 * 60 * 10))
                .signwith(getsigningkey())
                .compact();
    }

    public boolean validatetoken(string token, securitymember securitymember) {
        final string username = extractusername(token);
        return (username.equals(securitymember.getusername()) && !istokenexpired(token));
    }

    private boolean istokenexpired(string token) {
        return extractexpiration(token).before(new date(system.currenttimemillis()));
    }

    public date extractexpiration(string token) {
        return extractclaims(token,claims::getexpiration);
    }

    public
    string extractusername(string token) {
        return extractclaims(token,claims::getsubject);
    }


    private <t> t extractclaims(string token, function<claims, t> claimsresolver) {
        final jwe<claims> claims = extractallclaims(token);
        return claimsresolver.apply(claims.getpayload());
    }

    private jwe<claims> extractallclaims(string token) {
        try {
            return jwts.parser()
                            .requireissuer("http://localhost:8080")
                            .verifywith(getsigningkey())
                            .build()
                            .parse(token).accept(jwe.claims);
        } catch (jwtexception ex) {
            throw new jwtexception("wrong jwt"+ex.getmessage(),ex);
        }


    }
}
Copy after login

The issue is:

Caused by: io.jsonwebtoken.security.SignatureException: JWT signature does not match locally computed signature. JWT validity cannot be asserted and should not be trusted.
Copy after login

Solution

Your functiongetsigningkey() uses jwts.sig.hs512.key().build();, each A new key is created each time it is called.

But when you sign the token and verify the token you call getsigningkey() so you have different keys in both cases.

Instead create a key and store it and use the stored key. For example:

signingKey = getSigningKey();

// use it for signing
Jwts.builder().signWith(signingKey)...

// and verification
Jwts.parser().verifyWith(signingKey)...
Copy after login

But the creation of the key should not happen every time a token is created, but should be separated from it. You should also consider retaining the key so that you still have the same key after restarting the program. Otherwise, all issued tokens will become invalid after restarting.

Verification means that you verify the token signature against the same key used to sign it.

The above is the detailed content of Caught in an error. JWT validity cannot be asserted and should not be trusted. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)