Skip to content

Commit 961208a

Browse files
committed
feat: throw on init if invalid jwt config
1 parent 96fb0d0 commit 961208a

File tree

3 files changed

+33
-15
lines changed

3 files changed

+33
-15
lines changed

src/main/java/br/com/grupo63/techchallenge/common/api/controller/AbstractAPIController.java

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
import br.com.grupo63.techchallenge.common.exception.GenericException;
55
import br.com.grupo63.techchallenge.common.exception.NotFoundException;
66
import br.com.grupo63.techchallenge.common.exception.ValidationException;
7+
import org.slf4j.Logger;
8+
import org.slf4j.LoggerFactory;
79
import org.springframework.beans.factory.annotation.Autowired;
810
import org.springframework.context.MessageSource;
911
import org.springframework.context.i18n.LocaleContextHolder;
@@ -21,10 +23,11 @@ public abstract class AbstractAPIController {
2123
@Autowired
2224
private MessageSource messageSource;
2325

26+
private static final Logger logger = LoggerFactory.getLogger(AbstractAPIController.class);
27+
2428
@ExceptionHandler
2529
public ResponseEntity<DefaultResponseDTO> handleException(Exception exception) {
26-
27-
System.err.println("AbstractAPIController is handling expection:" + exception.getMessage());
30+
logger.warn("AbstractAPIController caught exception:");
2831
exception.printStackTrace();
2932

3033
DefaultResponseDTO responseDTO = new DefaultResponseDTO(

src/main/java/br/com/grupo63/techchallenge/common/config/JwtFilter.java

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,22 +16,30 @@
1616
public class JwtFilter implements Filter {
1717

1818
private final JwtService jwtService;
19+
private static final Logger log = LoggerFactory.getLogger(JwtFilter.class);
1920

2021
@Override
2122
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
2223
try {
2324
String authHeader = ((HttpServletRequest) request).getHeader("Authorization");
25+
log.debug("Auth header: {}", authHeader);
26+
2427
if (!StringUtils.hasLength(authHeader) || !StringUtils.startsWithIgnoreCase(authHeader, "Bearer ")) {
2528
throw new GeneralSecurityException("Missing or invalid authorization header");
2629
}
30+
2731
String jwt = authHeader.substring(7);
2832
Claims claims = jwtService.getClaims(jwt);
2933
request.setAttribute("clientId", claims.get("sub"));
34+
3035
filterChain.doFilter(request, response);
31-
} catch (Exception e) {
32-
((HttpServletResponse) response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
33-
response.getWriter().write("Unauthorized: Missing or incorrect JWT Token.");
36+
} catch (GeneralSecurityException e) {
37+
log.info("Unauthorized: {}", e.getMessage());
38+
response.getWriter().write("Unauthorized: Missing or incorrect JWT token.");
39+
} catch (RuntimeException e) {
40+
e.printStackTrace();
41+
((HttpServletResponse) response).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
42+
response.getWriter().write("Unexpected error during JWT filter");
3443
}
3544
}
36-
}
37-
45+
}

src/main/java/br/com/grupo63/techchallenge/common/config/JwtService.java

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,37 @@
11
package br.com.grupo63.techchallenge.common.config;
22

33
import io.jsonwebtoken.Claims;
4+
import io.jsonwebtoken.JwtParser;
45
import io.jsonwebtoken.Jwts;
56
import io.jsonwebtoken.io.Decoders;
7+
import org.slf4j.Logger;
8+
import org.slf4j.LoggerFactory;
69
import org.springframework.beans.factory.annotation.Value;
710
import org.springframework.stereotype.Service;
811

9-
import java.security.Key;
1012
import java.security.KeyFactory;
1113
import java.security.NoSuchAlgorithmException;
14+
import java.security.PublicKey;
1215
import java.security.spec.InvalidKeySpecException;
1316
import java.security.spec.X509EncodedKeySpec;
1417

1518
@Service
1619
public class JwtService {
20+
private static final Logger log = LoggerFactory.getLogger(JwtService.class);
1721

18-
@Value("${jwt.token.key.public}")
19-
private String jwtSigningKey;
22+
private final JwtParser parser;
2023

21-
public Claims getClaims(String token) throws NoSuchAlgorithmException, InvalidKeySpecException {
22-
return Jwts.parser().setSigningKey(getSigningKey()).build().parseClaimsJws(token)
23-
.getBody();
24+
public JwtService(@Value("${app.auth.jwt_public_key}") String jwtPublicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
25+
log.info("Initializing JWT Service\nPublic key: {}", jwtPublicKey);
26+
parser = Jwts.parser().verifyWith(getVerifyingKey(jwtPublicKey)).build();
2427
}
2528

26-
private Key getSigningKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
27-
byte[] keyBytes = Decoders.BASE64.decode(jwtSigningKey);
29+
public Claims getClaims(String token) {
30+
return parser.parseSignedClaims(token).getPayload();
31+
}
32+
33+
private PublicKey getVerifyingKey(String jwtPublicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
34+
byte[] keyBytes = Decoders.BASE64.decode(jwtPublicKey);
2835
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
2936
KeyFactory kf = KeyFactory.getInstance("RSA");
3037
return kf.generatePublic(spec);

0 commit comments

Comments
 (0)