Package org.mitre.oauth2.introspectingfilter

Examples of org.mitre.oauth2.introspectingfilter.IntrospectingTokenService$TokenCacheObject


      processRequestObject(inputParams.get("request"), request);
    }

    if (request.getClientId() != null) {
      try {
        ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId());

        if ((request.getScope() == null || request.getScope().isEmpty())) {
          Set<String> clientScopes = client.getScope();
          request.setScope(clientScopes);
        }

        if (request.getExtensions().get("max_age") == null && client.getDefaultMaxAge() != null) {
          request.getExtensions().put("max_age", client.getDefaultMaxAge().toString());
        }
      } catch (OAuth2Exception e) {
        logger.error("Caught OAuth2 exception trying to test client scopes and max age:", e);
      }
    }
View Full Code Here


        // need to check clientId first so that we can load the client to check other fields
        if (request.getClientId() == null) {
          request.setClientId(signedJwt.getJWTClaimsSet().getStringClaim("client_id"));
        }

        ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId());

        if (client == null) {
          throw new InvalidClientException("Client not found: " + request.getClientId());
        }


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

        if (client.getRequestObjectSigningAlg() == null ||
            !client.getRequestObjectSigningAlg().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 (alg.equals(JWSAlgorithm.RS256)
            || alg.equals(JWSAlgorithm.RS384)
            || alg.equals(JWSAlgorithm.RS512)) {

          // it's RSA, need to find the JWK URI and fetch the key

          if (client.getJwksUri() == null) {
            throw new InvalidClientException("Client must have a JWKS URI registered to use signed request objects.");
          }

          // check JWT signature
          JwtSigningAndValidationService validator = validators.getValidator(client.getJwksUri());

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

          if (!validator.validateSignature(signedJwt)) {
            throw new InvalidClientException("Signature did not validate for presented JWT request object.");
          }
        } else if (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 InvalidClientException("Unable to create signature validator for client's secret: " + client.getClientSecret());
          }

          if (!validator.validateSignature(signedJwt)) {
            throw new InvalidClientException("Signature did not validate for presented JWT request object.");
          }


        }


      } else if (jwt instanceof PlainJWT) {
        PlainJWT plainJwt = (PlainJWT)jwt;

        // need to check clientId first so that we can load the client to check other fields
        if (request.getClientId() == null) {
          request.setClientId(plainJwt.getJWTClaimsSet().getStringClaim("client_id"));
        }

        ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId());

        if (client == null) {
          throw new InvalidClientException("Client not found: " + request.getClientId());
        }

        if (client.getRequestObjectSigningAlg() == null) {
          throw new InvalidClientException("Client is not registered for unsigned request objects (no request_object_signing_alg registered)");
        } else if (!client.getRequestObjectSigningAlg().equals(Algorithm.NONE)) {
          throw new InvalidClientException("Client is not registered for unsigned request objects (request_object_signing_alg is " + client.getRequestObjectSigningAlg() +")");
        }

        // if we got here, we're OK, keep processing

      } else if (jwt instanceof EncryptedJWT) {

        EncryptedJWT encryptedJWT = (EncryptedJWT)jwt;

        // decrypt the jwt if we can

        encryptionService.decryptJwt(encryptedJWT);

        // TODO: what if the content is a signed JWT? (#525)

        if (!encryptedJWT.getState().equals(State.DECRYPTED)) {
          throw new InvalidClientException("Unable to decrypt the request object");
        }

        // need to check clientId first so that we can load the client to check other fields
        if (request.getClientId() == null) {
          request.setClientId(encryptedJWT.getJWTClaimsSet().getStringClaim("client_id"));
        }

        ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId());

        if (client == null) {
          throw new InvalidClientException("Client not found: " + request.getClientId());
        }
View Full Code Here

      return JsonEntityView.VIEWNAME;
    }

        OAuth2AccessTokenEntity accessToken = null;
        OAuth2RefreshTokenEntity refreshToken = null;
    ClientDetailsEntity tokenClient;
    Set<String> scopes;
    UserInfo user;

    try {

      // check access tokens first (includes ID tokens)
      accessToken = tokenServices.readAccessToken(tokenValue);

      tokenClient = accessToken.getClient();
      scopes = accessToken.getScope();

            user = userInfoService.getByUsernameAndClientId(accessToken.getAuthenticationHolder().getAuthentication().getName(), tokenClient.getClientId());

    } catch (InvalidTokenException e) {
      logger.info("Verify failed; Invalid access token. Checking refresh token.");
      try {

        // check refresh tokens next
        refreshToken = tokenServices.getRefreshToken(tokenValue);

        tokenClient = refreshToken.getClient();
        scopes = refreshToken.getAuthenticationHolder().getAuthentication().getOAuth2Request().getScope();

        user = userInfoService.getByUsernameAndClientId(refreshToken.getAuthenticationHolder().getAuthentication().getName(), tokenClient.getClientId());

      } catch (InvalidTokenException e2) {
        logger.error("Verify failed; Invalid access/refresh token", e2);
        Map<String,Boolean> entity = ImmutableMap.of("active", Boolean.FALSE);
        model.addAttribute("entity", entity);
        return JsonEntityView.VIEWNAME;
      }
    }

        // clientID is the principal name in the authentication
        String clientId = p.getName();
        ClientDetailsEntity authClient = clientService.loadClientByClientId(clientId);

        if (authClient.isAllowIntrospection()) {
            if (introspectionAuthorizer.isIntrospectionPermitted(authClient, tokenClient, scopes)) {
                // if it's a valid token, we'll print out information on it
                Map<String, Object> entity = accessToken != null
                        ? introspectionResultAssembler.assembleFrom(accessToken, user)
                        : introspectionResultAssembler.assembleFrom(refreshToken, user);
View Full Code Here

  @PreAuthorize("hasRole('ROLE_ADMIN')")
  @RequestMapping(value = "/client/{clientId}", method = RequestMethod.GET, produces = "application/json")
  public String getAccessTokensByClientId(@PathVariable("clientId") String clientId, ModelMap m, Principal p) {
   
    ClientDetailsEntity client = clientService.loadClientByClientId(clientId);
   
    if (client != null) {
      List<OAuth2AccessTokenEntity> tokens = tokenService.getAccessTokensForClient(client);
      m.put("entity", tokens);
      return TokenApiView.VIEWNAME;
View Full Code Here

  @PreAuthorize("hasRole('ROLE_ADMIN')")
  @RequestMapping(value = "/registration/{clientId}", method = RequestMethod.GET, produces = "application/json")
  public String getRegistrationTokenByClientId(@PathVariable("clientId") String clientId, ModelMap m, Principal p) {
   
    ClientDetailsEntity client = clientService.loadClientByClientId(clientId);
   
    if (client != null) {
      OAuth2AccessTokenEntity token = tokenService.getRegistrationAccessTokenForClient(client);
      if (token != null) {
        m.put("entity", token);
View Full Code Here

  }
 
  @PreAuthorize("hasRole('ROLE_ADMIN')")
  @RequestMapping(value = "/registration/{clientId}", method = RequestMethod.PUT, produces = "application/json")
  public String rotateRegistrationTokenByClientId(@PathVariable("clientId") String clientId, ModelMap m, Principal p) {
    ClientDetailsEntity client = clientService.loadClientByClientId(clientId);
   
    if (client != null) {
      OAuth2AccessTokenEntity token = oidcTokenService.rotateRegistrationAccessTokenForClient(client);
      token = tokenService.saveAccessToken(token);
     
View Full Code Here

      return HttpCodeView.VIEWNAME;
    }

    //AuthorizationRequest clientAuth = (AuthorizationRequest) model.remove("authorizationRequest");

    ClientDetailsEntity client = null;

    try {
      client = clientService.loadClientByClientId(authRequest.getClientId());
    } catch (OAuth2Exception e) {
      logger.error("confirmAccess: OAuth2Exception was thrown when attempting to load client", e);
      model.put("code", HttpStatus.BAD_REQUEST);
      return HttpCodeView.VIEWNAME;
    } catch (IllegalArgumentException e) {
      logger.error("confirmAccess: IllegalArgumentException was thrown when attempting to load client", e);
      model.put("code", HttpStatus.BAD_REQUEST);
      return HttpCodeView.VIEWNAME;
    }

    if (client == null) {
      logger.error("confirmAccess: could not find client " + authRequest.getClientId());
      model.put("code", HttpStatus.NOT_FOUND);
      return HttpCodeView.VIEWNAME;
    }

    model.put("auth_request", authRequest);
    model.put("client", client);

    String redirect_uri = authRequest.getRedirectUri();

    model.put("redirect_uri", redirect_uri);


    // pre-process the scopes
    Set<SystemScope> scopes = scopeService.fromStrings(authRequest.getScope());

    Set<SystemScope> sortedScopes = new LinkedHashSet<SystemScope>(scopes.size());
    Set<SystemScope> systemScopes = scopeService.getAll();

    // sort scopes for display based on the inherent order of system scopes
    for (SystemScope s : systemScopes) {
      if (scopes.contains(s)) {
        sortedScopes.add(s);
      }
    }

    // add in any scopes that aren't system scopes to the end of the list
    sortedScopes.addAll(Sets.difference(scopes, systemScopes));

    model.put("scopes", sortedScopes);

    // get the userinfo claims for each scope
    UserInfo user = userInfoService.getByUsername(p.getName());
    Map<String, Map<String, String>> claimsForScopes = new HashMap<String, Map<String, String>>();
    if (user != null) {
      JsonObject userJson = user.toJson();
 
      for (SystemScope systemScope : sortedScopes) {
        Map<String, String> claimValues = new HashMap<String, String>();
 
        Set<String> claims = scopeClaimTranslationService.getClaimsForScope(systemScope.getValue());
        for (String claim : claims) {
          if (userJson.has(claim) && userJson.get(claim).isJsonPrimitive()) {
            // TODO: this skips the address claim
            claimValues.put(claim, userJson.get(claim).getAsString());
          }
        }
 
        claimsForScopes.put(systemScope.getValue(), claimValues);
      }
    }

    model.put("claims", claimsForScopes);

    // client stats
    Integer count = statsService.getCountForClientId(client.getId());
    model.put("count", count);


    // contacts
    if (client.getContacts() != null) {
      String contacts = Joiner.on(", ").join(client.getContacts());
      model.put("contacts", contacts);
    }

    // if the client is over a week old and has more than one registration, don't give such a big warning
    // instead, tag as "Generally Recognized As Safe (gras)
    Date lastWeek = new Date(System.currentTimeMillis() + (60 * 60 * 24 * 7 * 1000));
    //Date lastWeek = new Date(System.currentTimeMillis() - (60 * 60 * 24 * 7 * 1000));
    if (count > 1 && client.getCreatedAt() != null && client.getCreatedAt().before(lastWeek)) {
      model.put("gras", true);
    } else {
      model.put("gras", false);
    }

View Full Code Here

   */
  @Test(expected = IllegalArgumentException.class)
  public void saveNewClient_badId() {

    // Set up a mock client.
    ClientDetailsEntity client = Mockito.mock(ClientDetailsEntity.class);
    Mockito.when(client.getId()).thenReturn(12345L); // doesn't matter what id it returns

    service.saveNewClient(client);
  }
View Full Code Here

   * Failure case of blacklisted client uri.
   */
  @Test(expected = IllegalArgumentException.class)
  public void saveNewClient_blacklisted() {

    ClientDetailsEntity client = Mockito.mock(ClientDetailsEntity.class);
    Mockito.when(client.getId()).thenReturn(null);

    String badUri = "badplace.xxx";

    Mockito.when(blacklistedSiteService.isBlacklisted(badUri)).thenReturn(true);
    Mockito.when(client.getRegisteredRedirectUri()).thenReturn(Sets.newHashSet(badUri));

    service.saveNewClient(client);
  }
View Full Code Here

  @Test
  public void saveNewClient_idWasAssigned() {

    // Set up a mock client.
    ClientDetailsEntity client = Mockito.mock(ClientDetailsEntity.class);
    Mockito.when(client.getId()).thenReturn(null);

    service.saveNewClient(client);

    Mockito.verify(client).setClientId(Matchers.anyString());
  }
View Full Code Here

TOP

Related Classes of org.mitre.oauth2.introspectingfilter.IntrospectingTokenService$TokenCacheObject

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.