Search in sources :

Example 61 with Token

use of com.auth0.json.mgmt.Token in project biosamples-v4 by EBIBioSamples.

the class AapClientService method getJwt.

public synchronized String getJwt() {
    if (username == null || username.trim().length() == 0 || password == null || password.trim().length() == 0) {
        return null;
    }
    // TODO refresh token when less than 5 minutes left, rather than when expired
    if (!jwt.isPresent() || (expiry.isPresent() && expiry.get().before(new Date()))) {
        String auth = username + ":" + password;
        byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(Charset.forName("US-ASCII")));
        String authHeader = "Basic " + new String(encodedAuth);
        RequestEntity<?> request = RequestEntity.get(aapUri).header(HttpHeaders.AUTHORIZATION, authHeader).build();
        ResponseEntity<String> response = restOperations.exchange(request, String.class);
        jwt = Optional.of(response.getBody());
        try {
            DecodedJWT decodedJwt = JWT.decode(jwt.get());
            expiry = Optional.of(decodedJwt.getExpiresAt());
        } catch (JWTDecodeException e) {
            // Invalid token
            throw new RuntimeException(e);
        }
        log.info("jwt = " + jwt);
    }
    return jwt.get();
}
Also used : JWTDecodeException(com.auth0.jwt.exceptions.JWTDecodeException) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Date(java.util.Date)

Example 62 with Token

use of com.auth0.json.mgmt.Token in project restheart by SoftInstigate.

the class JwtAuthenticationMechanism method authenticate.

@Override
public AuthenticationMechanism.AuthenticationMechanismOutcome authenticate(HttpServerExchange hse, SecurityContext sc) {
    try {
        String token = getToken(hse);
        if (token != null) {
            if (base64Encoded) {
                token = StringUtils.newStringUtf8(Base64.getUrlDecoder().decode(token));
            }
            DecodedJWT verifiedJwt = jwtVerifier.verify(token);
            String subject = verifiedJwt.getClaim(usernameClaim).asString();
            if (subject == null) {
                LOGGER.debug("username not specified with claim {}", usernameClaim);
                sc.authenticationFailed("JwtAuthenticationManager", "username not specified");
                return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
            Set<String> actualRoles = new LinkedHashSet<>();
            if (rolesClaim != null) {
                Claim _roles = verifiedJwt.getClaim(rolesClaim);
                if (_roles != null && !_roles.isNull()) {
                    try {
                        String[] __roles = _roles.asArray(String.class);
                        if (__roles != null) {
                            for (String role : __roles) {
                                actualRoles.add(role);
                            }
                        } else {
                            LOGGER.debug("roles is not an array: {}", _roles.asString());
                            return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
                        }
                    } catch (JWTDecodeException ex) {
                        LOGGER.warn("Jwt cannot get roles from claim {}, " + "extepected an array of strings: {}", rolesClaim, _roles.toString());
                    }
                }
            } else if (this.fixedRoles != null) {
                actualRoles.addAll(this.fixedRoles);
            }
            if (this.extraJwtVerifier != null) {
                this.extraJwtVerifier.accept(verifiedJwt);
            }
            var jwtPayload = new String(Base64.getUrlDecoder().decode(verifiedJwt.getPayload()), Charset.forName("UTF-8"));
            JwtAccount account = new JwtAccount(subject, actualRoles, jwtPayload);
            sc.authenticationComplete(account, "JwtAuthenticationManager", false);
            Request.of(hse).addXForwardedHeader("Jwt-Payload", jwtPayload);
            return AuthenticationMechanismOutcome.AUTHENTICATED;
        }
    } catch (JWTVerificationException ex) {
        LOGGER.debug("Jwt not verified: {}", ex.getMessage());
        return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
    }
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) JWTDecodeException(com.auth0.jwt.exceptions.JWTDecodeException) JwtAccount(org.restheart.security.JwtAccount) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Claim(com.auth0.jwt.interfaces.Claim)

Example 63 with Token

use of com.auth0.json.mgmt.Token in project conquery by bakdata.

the class ConqueryTokenRealm method doGetAuthenticationInfo.

@Override
public ConqueryAuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    if (!(TOKEN_CLASS.isAssignableFrom(token.getClass()))) {
        log.trace("Incompatible token. Expected {}, got {}", TOKEN_CLASS, token.getClass());
        return null;
    }
    log.trace("Token has expected format: {}\tWas: {} ", TOKEN_CLASS, token.getClass());
    DecodedJWT decodedToken = null;
    try {
        decodedToken = jwtConfig.getTokenVerifier(this).verify((String) token.getCredentials());
    } catch (TokenExpiredException e) {
        log.trace("The provided token is expired.");
        throw new ExpiredCredentialsException(e);
    } catch (SignatureVerificationException | InvalidClaimException e) {
        log.trace("The provided token was not successfully verified against its signature or claims.");
        throw new IncorrectCredentialsException(e);
    } catch (JWTVerificationException e) {
        log.trace("The provided token could not be verified.", e);
        throw new AuthenticationException(e);
    } catch (Exception e) {
        log.trace("Unable to decode token", e);
        throw new AuthenticationException(e);
    }
    log.trace("Received valid token.");
    String username = decodedToken.getSubject();
    UserId userId = UserId.Parser.INSTANCE.parse(username);
    final User user = getUserOrThrowUnknownAccount(storage, userId);
    return new ConqueryAuthenticationInfo(user, token, this, true);
}
Also used : User(com.bakdata.conquery.models.auth.entities.User) InvalidClaimException(com.auth0.jwt.exceptions.InvalidClaimException) TokenExpiredException(com.auth0.jwt.exceptions.TokenExpiredException) InvalidClaimException(com.auth0.jwt.exceptions.InvalidClaimException) SignatureVerificationException(com.auth0.jwt.exceptions.SignatureVerificationException) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) TokenExpiredException(com.auth0.jwt.exceptions.TokenExpiredException) UserId(com.bakdata.conquery.models.identifiable.ids.specific.UserId) ConqueryAuthenticationInfo(com.bakdata.conquery.models.auth.ConqueryAuthenticationInfo) SignatureVerificationException(com.auth0.jwt.exceptions.SignatureVerificationException) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 64 with Token

use of com.auth0.json.mgmt.Token in project teamapps by teamapps-org.

the class MediaSoupV3TokenGenerator method generateJwtToken.

public static String generateJwtToken(String secret, MediaSoupV3ApiOperation operation, String streamUuid, Duration tokenValidityDuration) {
    if (secret == null) {
        return "";
    }
    try {
        Algorithm algorithm = Algorithm.HMAC512(secret);
        JWTCreator.Builder builder = JWT.create();
        if (operation != null) {
            builder = builder.withClaim("operation", operation.ordinal());
        }
        if (streamUuid != null) {
            builder = builder.withClaim("stream", streamUuid);
        }
        if (tokenValidityDuration != null) {
            builder = builder.withExpiresAt(new Date(Instant.now().plus(tokenValidityDuration).toEpochMilli()));
        }
        return builder.sign(algorithm);
    } catch (JWTCreationException exception) {
        throw new RuntimeException("Could not create auth token - this should never happen!");
    }
}
Also used : JWTCreator(com.auth0.jwt.JWTCreator) Algorithm(com.auth0.jwt.algorithms.Algorithm) Date(java.util.Date) JWTCreationException(com.auth0.jwt.exceptions.JWTCreationException)

Example 65 with Token

use of com.auth0.json.mgmt.Token in project drug-formulary-ri by HL7-DaVinci.

the class IntrospectionEndpoint method handleIntrospection.

public static ResponseEntity<String> handleIntrospection(String token) {
    JSONObject response = new JSONObject();
    String baseUrl = AuthUtils.getFhirBaseUrl();
    try {
        Algorithm algorithm = Algorithm.RSA256(OauthEndpointController.getPublicKey(), null);
        JWTVerifier verifier = JWT.require(algorithm).withIssuer(baseUrl).withAudience(baseUrl).build();
        DecodedJWT jwt = verifier.verify(token);
        response.put("active", true);
        response.put("aud", jwt.getAudience().get(0));
        response.put("iss", jwt.getIssuer());
        // Display in sec not ms
        response.put("exp", jwt.getExpiresAt().getTime() / 1000);
        // Display in sec not ms
        response.put("iat", jwt.getIssuedAt().getTime() / 1000);
        response.put("patient_id", jwt.getClaim("patient_id").asString());
    } catch (JWTVerificationException exception) {
        response.put("active", false);
    }
    return new ResponseEntity<>(response.toString(), HttpStatus.OK);
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) ResponseEntity(org.springframework.http.ResponseEntity) JSONObject(org.json.JSONObject) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Aggregations

DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)276 Algorithm (com.auth0.jwt.algorithms.Algorithm)147 Test (org.junit.Test)120 JWTVerifier (com.auth0.jwt.JWTVerifier)97 Date (java.util.Date)78 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)62 IOException (java.io.IOException)59 Claim (com.auth0.jwt.interfaces.Claim)49 HashMap (java.util.HashMap)40 VoidRequest (com.auth0.net.VoidRequest)31 RSAPublicKey (java.security.interfaces.RSAPublicKey)31 Test (org.junit.jupiter.api.Test)30 JWTDecodeException (com.auth0.jwt.exceptions.JWTDecodeException)28 JWTCreator (com.auth0.jwt.JWTCreator)21 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)21 JWT (com.auth0.jwt.JWT)20 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)19 UnsupportedEncodingException (java.io.UnsupportedEncodingException)18 Instant (java.time.Instant)18 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)17