Package com.nimbusds.jwt

Examples of com.nimbusds.jwt.ReadOnlyJWTClaimsSet


      fail("URISyntaxException was thrown.");
    }

    UriComponents components = builder.build();
    String jwtString = components.getQueryParams().get("request").get(0);
    ReadOnlyJWTClaimsSet claims = null;

    try {
      SignedJWT jwt = SignedJWT.parse(jwtString);
      claims = jwt.getJWTClaimsSet();
    } catch (ParseException e) {
      fail("ParseException was thrown.");
    }

    assertEquals(responseType, claims.getClaim("response_type"));
    assertEquals(clientConfig.getClientId(), claims.getClaim("client_id"));

    List<String> scopeList = Arrays.asList(((String) claims.getClaim("scope")).split(" "));
    assertTrue(scopeList.containsAll(clientConfig.getScope()));

    assertEquals(redirectUri, claims.getClaim("redirect_uri"));
    assertEquals(nonce, claims.getClaim("nonce"));
    assertEquals(state, claims.getClaim("state"));
    for (String claim : options.keySet()) {
      assertEquals(options.get(claim), claims.getClaim(claim));
    }
  }
View Full Code Here


       * NOTE: Claims inside the request object always take precedence over those in the parameter map.
       */

      // now that we've got the JWT, and it's been parsed, validated, and/or decrypted, we can process the claims

      ReadOnlyJWTClaimsSet claims = jwt.getJWTClaimsSet();

      Set<String> responseTypes = OAuth2Utils.parseParameterList(claims.getStringClaim("response_type"));
      if (responseTypes != null && !responseTypes.isEmpty()) {
        if (!responseTypes.equals(request.getResponseTypes())) {
          logger.info("Mismatch between request object and regular parameter for response_type, using request object");
        }
        request.setResponseTypes(responseTypes);
      }

      String redirectUri = claims.getStringClaim("redirect_uri");
      if (redirectUri != null) {
        if (!redirectUri.equals(request.getRedirectUri())) {
          logger.info("Mismatch between request object and regular parameter for redirect_uri, using request object");
        }
        request.setRedirectUri(redirectUri);
      }

      String state = claims.getStringClaim("state");
      if(state != null) {
        if (!state.equals(request.getState())) {
          logger.info("Mismatch between request object and regular parameter for state, using request object");
        }
        request.setState(state);
      }

      String nonce = claims.getStringClaim("nonce");
      if(nonce != null) {
        if (!nonce.equals(request.getExtensions().get("nonce"))) {
          logger.info("Mismatch between request object and regular parameter for nonce, using request object");
        }
        request.getExtensions().put("nonce", nonce);
      }

      String display = claims.getStringClaim("display");
      if (display != null) {
        if (!display.equals(request.getExtensions().get("display"))) {
          logger.info("Mismatch between request object and regular parameter for display, using request object");
        }
        request.getExtensions().put("display", display);
      }

      String prompt = claims.getStringClaim("prompt");
      if (prompt != null) {
        if (!prompt.equals(request.getExtensions().get("prompt"))) {
          logger.info("Mismatch between request object and regular parameter for prompt, using request object");
        }
        request.getExtensions().put("prompt", prompt);
      }

      Set<String> scope = OAuth2Utils.parseParameterList(claims.getStringClaim("scope"));
      if (scope != null && !scope.isEmpty()) {
        if (!scope.equals(request.getScope())) {
          logger.info("Mismatch between request object and regular parameter for scope, using request object");
        }
        request.setScope(scope);
      }

      JsonObject claimRequest = parseClaimRequest(claims.getStringClaim("claims"));
      if (claimRequest != null) {
        if (!claimRequest.equals(parseClaimRequest(request.getExtensions().get("claims").toString()))) {
          logger.info("Mismatch between request object and regular parameter for claims, using request object");
        }
        // we save the string because the object might not be a Java Serializable, and we can parse it easily enough anyway
View Full Code Here

      try {
        JWT idToken = JWTParser.parse(idTokenValue);

        // validate our ID Token over a number of tests
        ReadOnlyJWTClaimsSet idClaims = idToken.getJWTClaimsSet();

        // check the signature
        JwtSigningAndValidationService jwtValidator = null;

        Algorithm tokenAlg = idToken.getHeader().getAlgorithm();
       
        Algorithm clientAlg = clientConfig.getIdTokenSignedResponseAlg();
       
        if (clientAlg != null) {
          if (!clientAlg.equals(tokenAlg)) {
            throw new AuthenticationServiceException("Token algorithm " + tokenAlg + " does not match expected algorithm " + clientAlg);
          }
        }
       
        if (idToken instanceof PlainJWT) {
         
          if (clientAlg == null) {
            throw new AuthenticationServiceException("Unsigned ID tokens can only be used if explicitly configured in client.");
          }
         
          if (tokenAlg != null && !tokenAlg.equals(JWSAlgorithm.NONE)) {
            throw new AuthenticationServiceException("Unsigned token received, expected signature with " + tokenAlg);
          }
        } else if (idToken instanceof SignedJWT) {
       
          SignedJWT signedIdToken = (SignedJWT)idToken;
         
          if (tokenAlg.equals(JWSAlgorithm.HS256)
            || tokenAlg.equals(JWSAlgorithm.HS384)
            || tokenAlg.equals(JWSAlgorithm.HS512)) {
           
            // generate one based on client secret
            jwtValidator = symmetricCacheService.getSymmetricValidtor(clientConfig.getClient());
          } else {
            // otherwise load from the server's public key
            jwtValidator = validationServices.getValidator(serverConfig.getJwksUri());
          }
         
          if (jwtValidator != null) {
            if(!jwtValidator.validateSignature(signedIdToken)) {
              throw new AuthenticationServiceException("Signature validation failed");
            }
          } else {
            logger.error("No validation service found. Skipping signature validation");
            throw new AuthenticationServiceException("Unable to find an appropriate signature validator for ID Token.");
          }
        } // TODO: encrypted id tokens

        // check the issuer
        if (idClaims.getIssuer() == null) {
          throw new AuthenticationServiceException("Id Token Issuer is null");
        } else if (!idClaims.getIssuer().equals(serverConfig.getIssuer())){
          throw new AuthenticationServiceException("Issuers do not match, expected " + serverConfig.getIssuer() + " got " + idClaims.getIssuer());
        }

        // check expiration
        if (idClaims.getExpirationTime() == null) {
          throw new AuthenticationServiceException("Id Token does not have required expiration claim");
        } else {
          // it's not null, see if it's expired
          Date now = new Date(System.currentTimeMillis() - (timeSkewAllowance * 1000));
          if (now.after(idClaims.getExpirationTime())) {
            throw new AuthenticationServiceException("Id Token is expired: " + idClaims.getExpirationTime());
          }
        }

        // check not before
        if (idClaims.getNotBeforeTime() != null) {
          Date now = new Date(System.currentTimeMillis() + (timeSkewAllowance * 1000));
          if (now.before(idClaims.getNotBeforeTime())){
            throw new AuthenticationServiceException("Id Token not valid untill: " + idClaims.getNotBeforeTime());
          }
        }

        // check issued at
        if (idClaims.getIssueTime() == null) {
          throw new AuthenticationServiceException("Id Token does not have required issued-at claim");
        } else {
          // since it's not null, see if it was issued in the future
          Date now = new Date(System.currentTimeMillis() + (timeSkewAllowance * 1000));
          if (now.before(idClaims.getIssueTime())) {
            throw new AuthenticationServiceException("Id Token was issued in the future: " + idClaims.getIssueTime());
          }
        }

        // check audience
        if (idClaims.getAudience() == null) {
          throw new AuthenticationServiceException("Id token audience is null");
        } else if (!idClaims.getAudience().contains(clientConfig.getClientId())) {
          throw new AuthenticationServiceException("Audience does not match, expected " + clientConfig.getClientId() + " got " + idClaims.getAudience());
        }

        // compare the nonce to our stored claim
        String nonce = idClaims.getStringClaim("nonce");
        if (Strings.isNullOrEmpty(nonce)) {

          logger.error("ID token did not contain a nonce claim.");

          throw new AuthenticationServiceException("ID token did not contain a nonce claim.");
        }

        String storedNonce = getStoredNonce(session);
        if (!nonce.equals(storedNonce)) {
          logger.error("Possible replay attack detected! The comparison of the nonce in the returned "
              + "ID Token to the session " + NONCE_SESSION_VARIABLE + " failed. Expected " + storedNonce + " got " + nonce + ".");

          throw new AuthenticationServiceException(
              "Possible replay attack detected! The comparison of the nonce in the returned "
                  + "ID Token to the session " + NONCE_SESSION_VARIABLE + " failed. Expected " + storedNonce + " got " + nonce + ".");
        }

        // pull the subject (user id) out as a claim on the id_token

        String userId = idClaims.getSubject();

        // construct an OIDCAuthenticationToken and return a Authentication object w/the userId and the idToken

        OIDCAuthenticationToken token = new OIDCAuthenticationToken(userId, idClaims.getIssuer(), serverConfig, idTokenValue, accessTokenValue, refreshTokenValue);

        Authentication authentication = this.getAuthenticationManager().authenticate(token);

        return authentication;
      } catch (ParseException e) {
View Full Code Here

    EncryptedJWT encryptedJwt = EncryptedJWT.parse(serialized);
    assertThat(encryptedJwt.getJWTClaimsSet(), nullValue());
    service.decryptJwt(encryptedJwt);

    ReadOnlyJWTClaimsSet resultClaims = encryptedJwt.getJWTClaimsSet();

    assertEquals(claimsSet.getIssuer(), resultClaims.getIssuer());
    assertEquals(claimsSet.getSubject(), resultClaims.getSubject());
  }
View Full Code Here

    EncryptedJWT encryptedJwt = EncryptedJWT.parse(serialized);
    assertThat(encryptedJwt.getJWTClaimsSet(), nullValue());
    service.decryptJwt(encryptedJwt);

    ReadOnlyJWTClaimsSet resultClaims = encryptedJwt.getJWTClaimsSet();

    assertEquals(claimsSet.getIssuer(), resultClaims.getIssuer());
    assertEquals(claimsSet.getSubject(), resultClaims.getSubject());
  }
View Full Code Here

    try {
      ClientDetailsEntity client = clientService.loadClientByClientId(jwtAuth.getClientId());

      JWT jwt = jwtAuth.getJwt();
      ReadOnlyJWTClaimsSet jwtClaims = jwt.getJWTClaimsSet();

      // check the signature with nimbus
      if (jwt instanceof SignedJWT) {
        SignedJWT jws = (SignedJWT)jwt;

        JWSAlgorithm alg = jws.getHeader().getAlgorithm();

        if (client.getTokenEndpointAuthSigningAlg() != null &&
            !client.getTokenEndpointAuthSigningAlg().equals(alg)) {
          throw new InvalidClientException("Client's registered request object signing algorithm (" + client.getRequestObjectSigningAlg() + ") does not match request object's actual algorithm (" + alg.getName() + ")");
        }

        if (client.getTokenEndpointAuthMethod() == null ||
            client.getTokenEndpointAuthMethod().equals(AuthMethod.NONE) ||
            client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_BASIC) ||
            client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_POST)) {
         
          // this client doesn't support this type of authentication
          throw new AuthenticationServiceException("Client does not support this authentication method.");
         
        } else if (client.getTokenEndpointAuthMethod().equals(AuthMethod.PRIVATE_KEY) &&
            (alg.equals(JWSAlgorithm.RS256)
                || alg.equals(JWSAlgorithm.RS384)
                || alg.equals(JWSAlgorithm.RS512))) {

          JwtSigningAndValidationService validator = validators.getValidator(client.getJwksUri());

          if (validator == null) {
            throw new AuthenticationServiceException("Unable to create signature validator for client's JWKS URI: " + client.getJwksUri());
          }

          if (!validator.validateSignature(jws)) {
            throw new AuthenticationServiceException("Signature did not validate for presented JWT authentication.");
          }
        } else if (client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_JWT) &&
            (alg.equals(JWSAlgorithm.HS256)
                || alg.equals(JWSAlgorithm.HS384)
                || alg.equals(JWSAlgorithm.HS512))) {

          // it's HMAC, we need to make a validator based on the client secret

          JwtSigningAndValidationService validator = symmetricCacheService.getSymmetricValidtor(client);

          if (validator == null) {
            throw new AuthenticationServiceException("Unable to create signature validator for client's secret: " + client.getClientSecret());
          }

          if (!validator.validateSignature(jws)) {
            throw new AuthenticationServiceException("Signature did not validate for presented JWT authentication.");
          }

        }
      }

      // check the issuer
      if (jwtClaims.getIssuer() == null) {
        throw new AuthenticationServiceException("Assertion Token Issuer is null");
      } else if (!jwtClaims.getIssuer().equals(client.getClientId())){
        throw new AuthenticationServiceException("Issuers do not match, expected " + client.getClientId() + " got " + jwtClaims.getIssuer());
      }

      // check expiration
      if (jwtClaims.getExpirationTime() == null) {
        throw new AuthenticationServiceException("Assertion Token does not have required expiration claim");
      } else {
        // it's not null, see if it's expired
        Date now = new Date(System.currentTimeMillis() - (timeSkewAllowance * 1000));
        if (now.after(jwtClaims.getExpirationTime())) {
          throw new AuthenticationServiceException("Assertion Token is expired: " + jwtClaims.getExpirationTime());
        }
      }

      // check not before
      if (jwtClaims.getNotBeforeTime() != null) {
        Date now = new Date(System.currentTimeMillis() + (timeSkewAllowance * 1000));
        if (now.before(jwtClaims.getNotBeforeTime())){
          throw new AuthenticationServiceException("Assertion Token not valid untill: " + jwtClaims.getNotBeforeTime());
        }
      }

      // check issued at
      if (jwtClaims.getIssueTime() != null) {
        // since it's not null, see if it was issued in the future
        Date now = new Date(System.currentTimeMillis() + (timeSkewAllowance * 1000));
        if (now.before(jwtClaims.getIssueTime())) {
          throw new AuthenticationServiceException("Assertion Token was issued in the future: " + jwtClaims.getIssueTime());
        }
      }

      // check audience
      if (jwtClaims.getAudience() == null) {
        throw new AuthenticationServiceException("Assertion token audience is null");
      } else if (!(jwtClaims.getAudience().contains(config.getIssuer()) || jwtClaims.getAudience().contains(config.getIssuer() + "token"))) {
        throw new AuthenticationServiceException("Audience does not match, expected " + config.getIssuer() + " or " + (config.getIssuer() + "token") + " got " + jwtClaims.getAudience());
      }

      // IFF we managed to get all the way down here, the token is valid
      return new JwtBearerAssertionAuthenticationToken(client.getClientId(), jwt, client.getAuthorities());

View Full Code Here

      if (softwareStatement.getState() == JWSObject.State.UNSIGNED) {
        throw new IllegalArgumentException("The software statement JWT must be signed");
      }

      ReadOnlyJWTClaimsSet claimsSet;

      try {
        claimsSet = softwareStatement.getJWTClaimsSet();

      } catch (java.text.ParseException e) {

        throw new IllegalArgumentException("The software statement is not a valid signed JWT: " + e.getMessage());
      }

      if (claimsSet.getIssuer() == null) {

        // http://tools.ietf.org/html/draft-ietf-oauth-dyn-reg-20#section-2.3
        throw new IllegalArgumentException("The software statement JWT must contain an 'iss' claim");
      }
View Full Code Here

    claimsSet.setSubject("alice");
    claimsSet.setAudience("client-123");
    claimsSet.setExpirationTime(new Date(3600000l));
    claimsSet.setIssueTime(new Date(1000l));

    ReadOnlyJWTClaimsSet roClaimsSet = (ReadOnlyJWTClaimsSet)claimsSet;

    IDTokenClaimsSet idTokenClaimsSet = new IDTokenClaimsSet(roClaimsSet);
    assertEquals("https://c2id.com", idTokenClaimsSet.getIssuer().getValue());
    assertEquals("alice", idTokenClaimsSet.getSubject().getValue());
    assertEquals("client-123", idTokenClaimsSet.getAudience().get(0).getValue());
View Full Code Here

      } else {
        // Request object inlined
        jwt = request.getRequestObject();
      }

      ReadOnlyJWTClaimsSet jwtClaims = decodeRequestObject(jwt);

      Map<String, String> requestObjectParams = reformatClaims(jwtClaims);

      Map<String, String> finalParams = new HashMap<>();
     
View Full Code Here

TOP

Related Classes of com.nimbusds.jwt.ReadOnlyJWTClaimsSet

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.