...
Para recibir el token en nuestro método REST, lo haremos en el header auth-token Authorization de la petición, y lo especificaremos en nuestros métodos Java con @RequestHeader, y podemos comprobarlo de la siguiente manera:
| Bloque de código | ||
|---|---|---|
| ||
@GetMapping("/titulaciones")
public ResponseEntity<List<TitulacionDTO>> titulaciones(@RequestHeader(value="auth-tokenAuthorization", required = true) String tokenCodificado) {
// Comprobamos el token
try {
jwtTokenUtil.getClaim( tokenCodificado );
} catch( final ServicioException e ) {
log.error( e.getLocalizedMessage() );
return new ResponseEntity<>( HttpStatus.FORBIDDEN );
}
} |
...
| Bloque de código | ||
|---|---|---|
| ||
@Log4j2
@Component
public class JwtTokenUtil {
@Value( "${es.um.jwt.secret}" )
private String secret;
// In minutes
@Value( "${es.um.jwt.expires}" )
private long expires;
/**
* Get the claim from the token If token expirated throw TokenExpiredException If token is invalid throw
* UnauthorizedException
*/
public Claims getClaim( String token ) {
final String[] tokenSplits = token.split( " " );
if ( !tokenSplits[0].equals( "Bearer" ) ) {
throw new UnauthorizedException();
} else {
token = tokenSplits[1];
try {
final Claims claims = Jwts.parser().setSigningKey( TextCodec.BASE64.encode( secret ) )
.parseClaimsJws( token ).getBody();
log.debug( "El claims es: " + claims.toString() );
log.debug( "El subject es: " + claims.getSubject() );
final Date expiration = claims.getExpiration();
if ( Instant.now().isAfter( expiration.toInstant() ) ) {
log.error( "Expiration Date: " + expiration.toString() );
log.error( "Current Instant: " + Instant.now().toString() );
log.error( "Error el token " + token + " está caducado" );
throw new TokenExpiredException();
}
return claims;
} catch ( final JwtException e ) {
log.error( "Error filtering:" + e );
throw new UnauthorizedException();
}
}
}
} |
Como vemos, tiene que ir anotada con @Component, y después la instanciaremos en nuestro controlador REST con @Autowired. También vemos que cogemos el valor del secret y de cuándo expira de nuestro application.properties. Podemos ver cómo funciona la parametrización en esta página de la wiki.
...