Search in sources :

Example 1 with UnauthorizedException

use of sic.controller.UnauthorizedException in project sic by belluccifranco.

the class JwtInterceptor method preHandle.

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    if (request.getMethod().equals("OPTIONS")) {
        return true;
    }
    final String authHeader = request.getHeader("Authorization");
    if (authHeader == null || !authHeader.startsWith("Bearer ")) {
        throw new UnauthorizedException(ResourceBundle.getBundle("Mensajes").getString("mensaje_error_token_vacio_invalido"));
    }
    // The part after "Bearer "
    final String token = authHeader.substring(7);
    Claims claims;
    try {
        claims = Jwts.parser().setSigningKey(secretkey).parseClaimsJws(token).getBody();
        request.setAttribute("claims", claims);
    } catch (JwtException ex) {
        throw new UnauthorizedException(ResourceBundle.getBundle("Mensajes").getString("mensaje_error_token_vacio_invalido"), ex);
    }
    long idUsuario = (int) claims.get("idUsuario");
    Usuario usuario = usuarioService.getUsuarioPorId(idUsuario);
    if (null == usuario || null == token) {
        throw new UnauthorizedException(ResourceBundle.getBundle("Mensajes").getString("mensaje_error_token_vacio_invalido"));
    } else if (!token.equalsIgnoreCase(usuario.getToken())) {
        throw new UnauthorizedException(ResourceBundle.getBundle("Mensajes").getString("mensaje_error_token_invalido"));
    }
    return true;
}
Also used : Claims(io.jsonwebtoken.Claims) Usuario(sic.modelo.Usuario) UnauthorizedException(sic.controller.UnauthorizedException) JwtException(io.jsonwebtoken.JwtException)

Aggregations

Claims (io.jsonwebtoken.Claims)1 JwtException (io.jsonwebtoken.JwtException)1 UnauthorizedException (sic.controller.UnauthorizedException)1 Usuario (sic.modelo.Usuario)1