Home  >  Article  >  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

王林
王林forward
2024-02-15 09:18:071187browse

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);
        }


    }
}

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.

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)...

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:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete