Search in sources :

Example 61 with JWTVerifier

use of com.auth0.jwt.JWTVerifier in project hopsworks by logicalclocks.

the class JWTController method verifyToken.

private DecodedJWT verifyToken(String token, String issuer, int expLeeway, Algorithm algorithm) throws VerificationException {
    DecodedJWT jwt = null;
    try {
        JWTVerifier verifier = JWT.require(algorithm).withIssuer(issuer).acceptExpiresAt(expLeeway).build();
        jwt = verifier.verify(token);
    } catch (Exception e) {
        throw new VerificationException(e.getMessage());
    }
    return jwt;
}
Also used : VerificationException(io.hops.hopsworks.jwt.exception.VerificationException) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) JWTVerifier(com.auth0.jwt.JWTVerifier) NotRenewableException(io.hops.hopsworks.jwt.exception.NotRenewableException) DuplicateSigningKeyException(io.hops.hopsworks.jwt.exception.DuplicateSigningKeyException) AccessLocalException(javax.ejb.AccessLocalException) SigningKeyNotFoundException(io.hops.hopsworks.jwt.exception.SigningKeyNotFoundException) JWTException(io.hops.hopsworks.jwt.exception.JWTException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) VerificationException(io.hops.hopsworks.jwt.exception.VerificationException) InvalidationException(io.hops.hopsworks.jwt.exception.InvalidationException)

Example 62 with JWTVerifier

use of com.auth0.jwt.JWTVerifier in project hopsworks by logicalclocks.

the class JWTFilter method jwtFilter.

public void jwtFilter(ContainerRequestContext requestContext) throws IOException {
    String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
    Object responseEntity;
    if (authorizationHeader == null) {
        LOGGER.log(Level.FINEST, "Authorization header not set.");
        responseEntity = responseEntity(Response.Status.UNAUTHORIZED, "Authorization header not set.");
        requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE).entity(responseEntity).build());
        return;
    }
    if (!authorizationHeader.startsWith(BEARER)) {
        LOGGER.log(Level.FINEST, "Invalid token. AuthorizationHeader : {0}", authorizationHeader);
        responseEntity = responseEntity(Response.Status.UNAUTHORIZED, "Invalidated token.");
        requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE).entity(responseEntity).build());
        return;
    }
    String token = authorizationHeader.substring(BEARER.length()).trim();
    DecodedJWT jwt = JWT.decode(token);
    Claim expLeewayClaim = jwt.getClaim(EXPIRY_LEEWAY);
    String issuer = getIssuer();
    int expLeeway = expLeewayClaim.asInt();
    try {
        Algorithm algorithm = getAlgorithm(jwt);
        JWTVerifier verifier = JWT.require(algorithm).withIssuer(issuer == null || issuer.isEmpty() ? jwt.getIssuer() : issuer).acceptExpiresAt(expLeeway == 0 ? DEFAULT_EXPIRY_LEEWAY : expLeeway).build();
        jwt = verifier.verify(token);
    } catch (Exception exception) {
        LOGGER.log(Level.FINE, "JWT Verification Exception: {0}", exception.getMessage());
        responseEntity = responseEntity(Response.Status.UNAUTHORIZED, exception.getMessage());
        requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE).entity(responseEntity).build());
        return;
    }
    if (!isTokenValid(jwt)) {
        LOGGER.log(Level.FINEST, "JWT Verification Exception: Invalidated token.");
        responseEntity = responseEntity(Response.Status.UNAUTHORIZED, "Invalidated token.");
        requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE).entity(responseEntity).build());
        return;
    }
    Claim rolesClaim = jwt.getClaim(ROLES);
    String[] userRoles = rolesClaim == null ? new String[0] : rolesClaim.asArray(String.class);
    Set<String> allowedRolesSet = allowedRoles();
    if (allowedRolesSet != null && !allowedRolesSet.isEmpty()) {
        if (!intersect(allowedRolesSet, Arrays.asList(userRoles))) {
            LOGGER.log(Level.FINE, "JWT Access Exception: Client not authorized for this invocation.");
            responseEntity = responseEntity(Response.Status.FORBIDDEN, "Client not authorized for this invocation.");
            requestContext.abortWith(Response.status(Response.Status.FORBIDDEN).entity(responseEntity).build());
            return;
        }
    }
    List<String> audience = jwt.getAudience();
    Set<String> accepts = acceptedTokens();
    if (accepts != null && !accepts.isEmpty()) {
        if (!intersect(accepts, audience)) {
            LOGGER.log(Level.FINE, "JWT Access Exception: Token not issued for this recipient.");
            responseEntity = responseEntity(Response.Status.FORBIDDEN, "Token not issued for this recipient.");
            requestContext.abortWith(Response.status(Response.Status.FORBIDDEN).entity(responseEntity).build());
            return;
        }
    }
    postJWTFilter(requestContext, jwt);
}
Also used : DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) Claim(com.auth0.jwt.interfaces.Claim) IOException(java.io.IOException) SigningKeyNotFoundException(io.hops.hopsworks.jwt.exception.SigningKeyNotFoundException)

Example 63 with JWTVerifier

use of com.auth0.jwt.JWTVerifier in project atjob by 1-2-3.

the class JwtUtil method verify.

/**
 * 校验 token是否正确.
 *
 * @param token 密钥
 * @param secret 用户的密码
 * @return 是否正确
 */
public static boolean verify(String token, String username, String secret) {
    try {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
        verifier.verify(token);
        return true;
    } catch (Exception e) {
        return false;
    }
}
Also used : Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) JWTDecodeException(com.auth0.jwt.exceptions.JWTDecodeException)

Example 64 with JWTVerifier

use of com.auth0.jwt.JWTVerifier in project rsocket-graphql-gateway by alibaba-rsocket-broker.

the class JwtAuthenticationServiceImpl method auth.

@Override
@Nullable
public NamedPrincipal auth(String jwtToken) {
    int tokenHashCode = jwtToken.hashCode();
    NamedPrincipal principal = jwtVerifyCache.getIfPresent(tokenHashCode);
    if (principal == null) {
        for (JWTVerifier verifier : verifiers) {
            try {
                DecodedJWT decodedJWT = verifier.verify(jwtToken);
                principal = new NamedPrincipal(decodedJWT.getSubject());
                jwtVerifyCache.put(tokenHashCode, principal);
                break;
            } catch (JWTVerificationException ignore) {
            }
        }
    }
    return principal;
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) JWTVerifier(com.auth0.jwt.interfaces.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Nullable(org.jetbrains.annotations.Nullable)

Example 65 with JWTVerifier

use of com.auth0.jwt.JWTVerifier in project framework by galasa-dev.

the class JwtAuthFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
        chain.doFilter(request, response);
        return;
    }
    HttpServletRequest servletRequest = (HttpServletRequest) request;
    HttpServletResponse servletResponse = (HttpServletResponse) response;
    if ("/auth".equals(servletRequest.getServletPath())) {
        // dont do this for the auth url
        chain.doFilter(request, response);
        return;
    }
    Principal principal = servletRequest.getUserPrincipal();
    if (principal != null) {
        // already authenticated
        chain.doFilter(request, response);
        return;
    }
    String authorization = servletRequest.getHeader("Authorization");
    if (authorization == null) {
        chain.doFilter(request, response);
        return;
    }
    StringTokenizer st = new StringTokenizer(authorization);
    if (!st.hasMoreTokens()) {
        chain.doFilter(request, response);
        return;
    }
    String bearer = st.nextToken();
    if (!"bearer".equalsIgnoreCase(bearer)) {
        chain.doFilter(request, response);
        return;
    }
    if (!st.hasMoreTokens()) {
        chain.doFilter(request, response);
        return;
    }
    String sJwt = st.nextToken();
    Algorithm algorithm = Algorithm.HMAC256(this.configurationProperties.getProperty(SECRET_KEY));
    JWTVerifier verifier = JWT.require(algorithm).withIssuer("galasa").build();
    try {
        DecodedJWT jwt = verifier.verify(sJwt);
        String subject = jwt.getSubject();
        String role = jwt.getClaim("role").asString();
        JwtRequestWrapper wrapper = new JwtRequestWrapper(subject, role, servletRequest);
        chain.doFilter(wrapper, servletResponse);
        return;
    } catch (AlgorithmMismatchException e) {
        chain.doFilter(request, response);
        invalidAuth(servletRequest, servletResponse, "Incorrect Algorithim " + e);
        return;
    } catch (SignatureVerificationException e) {
        chain.doFilter(request, response);
        invalidAuth(servletRequest, servletResponse, "Non valid signature " + e);
    } catch (TokenExpiredException e) {
        chain.doFilter(request, response);
        invalidAuth(servletRequest, servletResponse, "Jwt has expired " + e);
    } catch (InvalidClaimException e) {
        chain.doFilter(request, response);
        invalidAuth(servletRequest, servletResponse, "Invalid Claims " + e);
    }
// chain.doFilter(servletRequest, servletResponse);
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) InvalidClaimException(com.auth0.jwt.exceptions.InvalidClaimException) Algorithm(com.auth0.jwt.algorithms.Algorithm) AlgorithmMismatchException(com.auth0.jwt.exceptions.AlgorithmMismatchException) HttpServletRequest(javax.servlet.http.HttpServletRequest) StringTokenizer(java.util.StringTokenizer) TokenExpiredException(com.auth0.jwt.exceptions.TokenExpiredException) SignatureVerificationException(com.auth0.jwt.exceptions.SignatureVerificationException) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Principal(java.security.Principal)

Aggregations

JWTVerifier (com.auth0.jwt.JWTVerifier)115 Algorithm (com.auth0.jwt.algorithms.Algorithm)104 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)100 Test (org.junit.Test)42 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)30 IOException (java.io.IOException)23 JWTVerifier (com.auth0.jwt.interfaces.JWTVerifier)18 RSAPublicKey (java.security.interfaces.RSAPublicKey)15 JWTDecodeException (com.auth0.jwt.exceptions.JWTDecodeException)14 Claim (com.auth0.jwt.interfaces.Claim)10 Date (java.util.Date)9 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 HashMap (java.util.HashMap)8 ECKey (java.security.interfaces.ECKey)7 ServletException (javax.servlet.ServletException)7 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 TokenExpiredException (com.auth0.jwt.exceptions.TokenExpiredException)5 RSAKeyProvider (com.auth0.jwt.interfaces.RSAKeyProvider)5 URL (java.net.URL)5 KeyFactory (java.security.KeyFactory)5