Have following JWTTokenService class:
package com.project.blogapi.security;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.util.Date;
import static java.lang.System.*;
@Service
public class JWTTokenService implements TokenService {
private final Algorithm algorithm;
private final String SIGNING_KEY;
private final long TOKEN_EXPIRY_MILLIS = (1000 * 60 * 60 * 24);
private final String ISSUER = "blog-api";
public JWTTokenService(String signingKey) {
SIGNING_KEY = signingKey;
this.algorithm = Algorithm.HMAC256(SIGNING_KEY);
}
@Override
public String createAuthToken(String username) {
String token = JWT.create()
.withIssuer(ISSUER)
.withIssuedAt(new java.util.Date())
.withExpiresAt(new java.util.Date(System.currentTimeMillis() + TOKEN_EXPIRY_MILLIS))
.withSubject(username)
.sign(algorithm);
return token;
}
@Override
public String getUsernameFromToken(String token) throws IllegalStateException {
var verifier = JWT.require(algorithm)
.withIssuer(ISSUER)
.build();
var decodedToken = verifier.verify(token);
return decodedToken.getSubject();
}
}
have a TokeService Interface:
package com.project.blogapi.security;
public interface TokenService {
/*
create a JWT or Service side token for given username
*/
String createAuthToken(String username);
String getUsernameFromToken(String token) throws IllegalStateException;
}
and a JWTTokenProperties to create JWTTokenService with value ideally coming from application.properties
package com.project.blogapi.security;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class JWTTokenProperties {
public static @Value("${key}") String SIGNING_KEY;
public static JWTTokenService create(){
return new JWTTokenService(SIGNING_KEY);
}
}
have tried different ways but SIGNING_KEY is always null
tried without tokenproperties directly wiht jwttokenservices. did not work.
Remove static modifier like so: