Search in sources :

Example 81 with JWT

use of com.auth0.android.jwt.JWT in project balcaovirtual by trf2-jus-br.

the class AutenticarPost method verify.

public static Map<String, Object> verify(String jwt) throws SwaggerAuthorizationException {
    final JWTVerifier verifier = new JWTVerifier(Utils.getJwtPassword());
    Map<String, Object> map;
    try {
        map = verifier.verify(jwt);
    } catch (InvalidKeyException | NoSuchAlgorithmException | IllegalStateException | SignatureException | IOException | JWTVerifyException e) {
        throw new SwaggerAuthorizationException(e);
    }
    return map;
}
Also used : JWTVerifyException(com.auth0.jwt.JWTVerifyException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) JWTVerifier(com.auth0.jwt.JWTVerifier) SwaggerAuthorizationException(com.crivano.swaggerservlet.SwaggerAuthorizationException)

Example 82 with JWT

use of com.auth0.android.jwt.JWT in project iet-hf-2022-k-k-k-k-k-k by BME-MIT-IET.

the class TokenController method post.

@ApiOperation("AuthChecking")
@PostMapping("/hasRightForPage")
public ResponseEntity<PageAuthorizationResponse> post(@RequestHeader HttpHeaders headers, @RequestBody PageAuthorizationRequest body) {
    String authHeader = headers.getFirst(HttpHeaders.AUTHORIZATION);
    String route = body.getRoute();
    if (PageAuthorizationChecker.noRightPages().contains(route)) {
        return new ResponseEntity<>(PageAuthorizationResponse.hasRight, HttpStatus.OK);
    }
    if (authHeader == null) {
        return new ResponseEntity<>(PageAuthorizationResponse.tokenExpired, HttpStatus.OK);
    } else if (authHeader.startsWith("Bearer") && authHeader.length() < 7) {
        return new ResponseEntity<>(PageAuthorizationResponse.tokenExpired, HttpStatus.OK);
    }
    try {
        DecodedJWT jwt = JwtUtil.getDecodedJWT(authHeader);
        if (jwt.getExpiresAt().before(new Date())) {
            return new ResponseEntity<>(PageAuthorizationResponse.tokenExpired, HttpStatus.OK);
        }
        Collection<Role> rolesOfUser = this.personService.getByUsername(JwtUtil.getUsernameFromJwt(authHeader)).getRoles();
        if (PageAuthorizationChecker.hasRightForPage(route, rolesOfUser)) {
            return new ResponseEntity<>(PageAuthorizationResponse.hasRight, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(PageAuthorizationResponse.noRight, HttpStatus.OK);
        }
    } catch (Exception e) {
        return new ResponseEntity<>(PageAuthorizationResponse.tokenExpired, HttpStatus.OK);
    }
}
Also used : Role(com.adja.evchargerappserver.api.role.Role) ResponseEntity(org.springframework.http.ResponseEntity) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Date(java.util.Date) IOException(java.io.IOException) ApiOperation(io.swagger.annotations.ApiOperation)

Example 83 with JWT

use of com.auth0.android.jwt.JWT in project tanafaso-backend by tanafaso.

the class ApiAuthenticationController method validateAppleAuthCode.

private boolean validateAppleAuthCode(AppleAuthenticationRequest request) {
    Map<String, Object> appleApiRequestHeader = new HashMap<>();
    appleApiRequestHeader.put("alg", "ES256");
    appleApiRequestHeader.put("kid", appleSignInKeyId);
    appleApiRequestHeader.put("typ", "JWT");
    InputStreamReader appleAuthPrivateKeyInputStreamReader;
    try {
        appleAuthPrivateKeyInputStreamReader = new InputStreamReader(new ClassPathResource(appleAuthPrivateKeyFile).getInputStream());
    } catch (IOException e) {
        logger.error("Couldn't read the apple authorization private key file.", e);
        return false;
    }
    ECPrivateKey privateKey;
    try {
        PemObject pemObject;
        pemObject = new PemReader(appleAuthPrivateKeyInputStreamReader).readPemObject();
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(pemObject.getContent());
        KeyFactory factory;
        factory = KeyFactory.getInstance("EC");
        privateKey = (ECPrivateKey) factory.generatePrivate(spec);
    } catch (Exception e) {
        logger.error("Could not convert Apple private key into an EC key.", e);
        return false;
    }
    String signedJwt = JWT.create().withHeader(appleApiRequestHeader).withIssuer(appleTeamId).withIssuedAt(new Date(System.currentTimeMillis())).withExpiresAt(new Date(System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(10))).withAudience("https://appleid.apple.com").withSubject("com.tanafaso.azkar").sign(Algorithm.ECDSA256(privateKey));
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    map.add("client_id", "com.tanafaso.azkar");
    map.add("client_secret", signedJwt);
    map.add("code", request.getAuthCode());
    map.add("grant_type", "authorization_code");
    HttpEntity<MultiValueMap<String, String>> appleApiRequestHttpEntity = new HttpEntity<>(map, headers);
    logger.info("Sending to Apple auth code verification API.");
    ResponseEntity<AppleIdToken> appleIdToken = restTemplate.postForEntity("https://appleid.apple.com/auth/token", appleApiRequestHttpEntity, AppleIdToken.class);
    if (appleIdToken.getStatusCode() == HttpStatus.OK) {
        DecodedJWT decodedJwt = JWT.decode(appleIdToken.getBody().getIdToken());
        boolean emailIsVerified = decodedJwt.getClaim("email_verified").asString().equals("true");
        String potentiallyVerifiedEmail = decodedJwt.getClaim("email").asString().toLowerCase();
        if (emailIsVerified && potentiallyVerifiedEmail.equals(request.getEmail())) {
            return true;
        }
        logger.info("Failed to verify user signing in with apple: email={}, firstName={}, " + "lastName={}, emailIsVerified={}, appleApiReturnedEmail={}", request.getEmail(), request.getFirstName(), request.getLastName(), emailIsVerified, potentiallyVerifiedEmail);
        return false;
    }
    logger.info("Failed to verify user signing in with apple as apple API returned status code: " + "{} for email={}, firstName={}, lastName={}", appleIdToken.getStatusCode().toString(), request.getEmail(), request.getFirstName(), request.getLastName());
    return false;
}
Also used : ECPrivateKey(java.security.interfaces.ECPrivateKey) HttpHeaders(org.springframework.http.HttpHeaders) InputStreamReader(java.io.InputStreamReader) HttpEntity(org.springframework.http.HttpEntity) HashMap(java.util.HashMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) IOException(java.io.IOException) ClassPathResource(org.springframework.core.io.ClassPathResource) MessagingException(javax.mail.MessagingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) Date(java.util.Date) PemObject(org.bouncycastle.util.io.pem.PemObject) PemReader(org.bouncycastle.util.io.pem.PemReader) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) PemObject(org.bouncycastle.util.io.pem.PemObject) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) KeyFactory(java.security.KeyFactory) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap)

Example 84 with JWT

use of com.auth0.android.jwt.JWT in project brapi-Java-TestServer by plantbreeding.

the class BrapiTestServerJWTAuthFilter method validateOAuthToken.

private String validateOAuthToken(HttpServletRequest request) {
    try {
        String token = request.getHeader("Authorization");
        if (token != null) {
            token = token.replaceFirst("Bearer ", "");
            RSAPublicKey pubKey = getPublicKey(oidcDiscoveryUrl);
            Algorithm algorithm = Algorithm.RSA256(pubKey, null);
            JWTVerifier verifier = JWT.require(algorithm).withIssuer("https://auth.brapi.org/auth/realms/brapi").build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaim("email").asString();
        }
        return null;
    } catch (Exception e) {
        return null;
    }
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.interfaces.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) ServletException(javax.servlet.ServletException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) FileNotFoundException(java.io.FileNotFoundException)

Example 85 with JWT

use of com.auth0.android.jwt.JWT in project vars-annotation by mbari-media-management.

the class BasicJWTAuthInterceptor method isExpired.

private boolean isExpired(Authorization a) {
    try {
        DecodedJWT jwt = JWT.decode(a.getAccessToken());
        Instant iat = jwt.getExpiresAt().toInstant();
        return iat.isBefore(Instant.now());
    } catch (Exception e) {
        return true;
    }
}
Also used : Instant(java.time.Instant) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) IOException(java.io.IOException)

Aggregations

DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)305 Test (org.junit.Test)217 Algorithm (com.auth0.jwt.algorithms.Algorithm)110 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)82 JWTVerifier (com.auth0.jwt.JWTVerifier)79 IOException (java.io.IOException)60 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)54 ECDSAAlgorithmTest (com.auth0.jwt.algorithms.ECDSAAlgorithmTest)53 Date (java.util.Date)50 Claim (com.auth0.jwt.interfaces.Claim)36 RSAPublicKey (java.security.interfaces.RSAPublicKey)34 ECPublicKey (java.security.interfaces.ECPublicKey)27 ECDSAKeyProvider (com.auth0.jwt.interfaces.ECDSAKeyProvider)26 HashMap (java.util.HashMap)25 JWTDecodeException (com.auth0.jwt.exceptions.JWTDecodeException)20 Instant (java.time.Instant)20 JsonObject (com.google.gson.JsonObject)19 ServletException (javax.servlet.ServletException)19 JWT (com.auth0.jwt.JWT)18 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)18