0% found this document useful (0 votes)
2 views2 pages

Notas 3

The document contains two implementations of a JwtInterceptor class in Java, which is used to validate JWT tokens in HTTP requests. The first implementation checks for a Bearer token in the Authorization header and parses it using a public key, while the second implementation uses constructor injection for the public key and includes a separate validateToken method for token validation. Both implementations return unauthorized responses for missing or invalid tokens.

Uploaded by

Chilinssky Che
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Notas 3

The document contains two implementations of a JwtInterceptor class in Java, which is used to validate JWT tokens in HTTP requests. The first implementation checks for a Bearer token in the Authorization header and parses it using a public key, while the second implementation uses constructor injection for the public key and includes a separate validateToken method for token validation. Both implementations return unauthorized responses for missing or invalid tokens.

Uploaded by

Chilinssky Che
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import io.jsonwebtoken.

Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;

@Component
public class JwtInterceptor implements HandlerInterceptor {

@Autowired
private PublicKey publicKey;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse
response, Object handler) throws Exception {
String authHeader = request.getHeader("Authorization");

if (authHeader == null || !authHeader.startsWith("Bearer ")) {


response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing or
invalid Authorization header");
return false;
}

String token = authHeader.substring(7);

try {
Claims claims = Jwts.parserBuilder()
.setSigningKey(publicKey)
.build()
.parseClaimsJws(token)
.getBody();

// Puedes acceder a los claims del token si es necesario


String userId = claims.getSubject();
request.setAttribute("userId", userId);

} catch (JwtException e) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid
token");
return false;
}

return true;
}
}

***********************************************************************************
***********************************************************************************
*
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;

@Component
public class JwtInterceptor implements HandlerInterceptor {

private final PublicKey publicKey;

// Inyecta la PublicKey usando constructor


public JwtInterceptor(PublicKey publicKey) {
this.publicKey = publicKey;
}

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse
response, Object handler) throws Exception {
String token = request.getHeader("Authorization");

// Verifica que el token no sea nulo o vacío


if (token == null || token.isEmpty()) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}

try {
// Llama al método validateToken para validar el JWT
Claims claims = validateToken(token.replace("Bearer ", ""), publicKey);
// Puedes agregar más lógica aquí, como verificar roles o permisos

// Si el token es válido, continúa con la solicitud


return true;
} catch (Exception e) {
// Si la validación falla, devuelve una respuesta 401
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
}

// Método validateToken previamente proporcionado


private Claims validateToken(String token, PublicKey publicKey) {
try {
return Jwts.parserBuilder()
.setSigningKey(publicKey)
.build()
.parseClaimsJws(token)
.getBody();
} catch (Exception e) {
throw new RuntimeException("Invalid token.");
}
}
}

***********************************************************************************
*****************

You might also like