Package org.mitre.oauth2.model

Examples of org.mitre.oauth2.model.RegisteredClient


  // sucess, false otherwise.
  private boolean parseToken(String accessToken) {

    // find out which URL to ask
    String introspectionUrl;
    RegisteredClient client;
    try {
      introspectionUrl = introspectionConfigurationService.getIntrospectionUrl(accessToken);
      client = introspectionConfigurationService.getClientConfiguration(accessToken);
    } catch (IllegalArgumentException e) {
      logger.error("Unable to load introspection URL or client configuration", e);
      return false;
    }
    // Use the SpringFramework RestTemplate to send the request to the
    // endpoint
    String validatedToken = null;

    RestTemplate restTemplate;
    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();

    final String clientId = client.getClientId();
    final String clientSecret = client.getClientSecret();

    if (SECRET_BASIC.equals(client.getTokenEndpointAuthMethod())){
      // use BASIC auth if configured to do so
      restTemplate = new RestTemplate(factory) {

        @Override
        protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
View Full Code Here


        "   \"contacts\": [\"ve7jtb@example.org\", \"mary@example.org\"],\n" +
        "   \"request_uris\":\n" +
        "     [\"https://client.example.org/rf.txt#qpXaRLh_n93TTR9F252ValdatUQvQiJi5BDub2BeznA\"]\n" +
        "  }";

    RegisteredClient c = ClientDetailsEntityJsonProcessor.parseRegistered(json);


    assertEquals("s6BhdRkqt3", c.getClientId());
    assertEquals("ZJYCqe3GGRvdrudKyZS0XhGv_Z45DuKhCUk0gBR1vZk", c.getClientSecret());
    assertEquals(new Date(1577858400L * 1000L), c.getClientSecretExpiresAt());
    assertEquals("this.is.an.access.token.value.ffx83", c.getRegistrationAccessToken());
    assertEquals("https://server.example.com/connect/register?client_id=s6BhdRkqt3", c.getRegistrationClientUri());
    assertEquals(ClientDetailsEntity.AppType.WEB, c.getApplicationType());
    assertEquals(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2"), c.getRedirectUris());
    assertEquals("My Example", c.getClientName());
    assertEquals(ImmutableSet.of("code", "token"), c.getResponseTypes());
    assertEquals(ImmutableSet.of("authorization_code", "implicit"), c.getGrantTypes());
    assertEquals("https://client.example.org/logo.png", c.getLogoUri());
    assertEquals(ClientDetailsEntity.SubjectType.PAIRWISE, c.getSubjectType());
    assertEquals("https://other.example.net/file_of_redirect_uris.json", c.getSectorIdentifierUri());
    assertEquals(ClientDetailsEntity.AuthMethod.SECRET_BASIC, c.getTokenEndpointAuthMethod());
    assertEquals("https://client.example.org/my_public_keys.jwks", c.getJwksUri());
    assertEquals(JWEAlgorithm.RSA1_5, c.getUserInfoEncryptedResponseAlg());
    assertEquals(EncryptionMethod.A128CBC_HS256, c.getUserInfoEncryptedResponseEnc());
    assertEquals(ImmutableSet.of("ve7jtb@example.org", "mary@example.org"), c.getContacts());
    assertEquals(ImmutableSet.of("https://client.example.org/rf.txt#qpXaRLh_n93TTR9F252ValdatUQvQiJi5BDub2BeznA"), c.getRequestUris());

  }
View Full Code Here

    String issuer = getIssuer(accessToken);
    if (!Strings.isNullOrEmpty(issuer)) {
      ServerConfiguration server = serverConfigurationService.getServerConfiguration(issuer);
      if (server != null) {
        RegisteredClient client = clientConfigurationService.getClientConfiguration(server);
        if (client != null) {
          return client;
        } else {
          throw new IllegalArgumentException("Could not find client configuration for issuer " + issuer);
        }
View Full Code Here

  /**
   * Test method for {@link org.mitre.openid.connect.ClientDetailsEntityJsonProcessor#serialize(org.mitre.oauth2.model.RegisteredClient)}.
   */
  @Test
  public void testSerialize() {
    RegisteredClient c = new RegisteredClient();

    c.setClientId("s6BhdRkqt3");
    c.setClientSecret("ZJYCqe3GGRvdrudKyZS0XhGv_Z45DuKhCUk0gBR1vZk");
    c.setClientSecretExpiresAt(new Date(1577858400L * 1000L));
    c.setRegistrationAccessToken("this.is.an.access.token.value.ffx83");
    c.setRegistrationClientUri("https://server.example.com/connect/register?client_id=s6BhdRkqt3");
    c.setApplicationType(ClientDetailsEntity.AppType.WEB);
    c.setRedirectUris(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2"));
    c.setClientName("My Example");
    c.setResponseTypes(ImmutableSet.of("code", "token"));
    c.setGrantTypes(ImmutableSet.of("authorization_code", "implicit"));
    c.setLogoUri("https://client.example.org/logo.png");
    c.setSubjectType(ClientDetailsEntity.SubjectType.PAIRWISE);
    c.setSectorIdentifierUri("https://other.example.net/file_of_redirect_uris.json");
    c.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.SECRET_BASIC);
    c.setJwksUri("https://client.example.org/my_public_keys.jwks");
    c.setUserInfoEncryptedResponseAlg(JWEAlgorithm.RSA1_5);
    c.setUserInfoEncryptedResponseEnc(EncryptionMethod.A128CBC_HS256);
    c.setContacts(ImmutableSet.of("ve7jtb@example.org", "mary@example.org"));
    c.setRequestUris(ImmutableSet.of("https://client.example.org/rf.txt#qpXaRLh_n93TTR9F252ValdatUQvQiJi5BDub2BeznA"));

    JsonObject j = ClientDetailsEntityJsonProcessor.serialize(c);

    assertEquals("s6BhdRkqt3", j.get("client_id").getAsString());
    assertEquals("ZJYCqe3GGRvdrudKyZS0XhGv_Z45DuKhCUk0gBR1vZk", j.get("client_secret").getAsString());
View Full Code Here

    if (jsonEl.isJsonObject()) {

      JsonObject o = jsonEl.getAsJsonObject();
      ClientDetailsEntity c = parse(jsonEl);

      RegisteredClient rc = new RegisteredClient(c);
      // get any fields from the registration
      rc.setRegistrationAccessToken(getAsString(o, "registration_access_token"));
      rc.setRegistrationClientUri(getAsString(o, "registration_client_uri"));
      rc.setClientIdIssuedAt(getAsDate(o, "client_id_issued_at"));
      rc.setClientSecretExpiresAt(getAsDate(o, "client_secret_expires_at"));

      return rc;
    } else {
      return null;
    }
View Full Code Here

      }


      session.setAttribute(ISSUER_SESSION_VARIABLE, serverConfig.getIssuer());

      RegisteredClient clientConfig = clients.getClientConfiguration(serverConfig);
      if (clientConfig == null) {
        logger.error("No client configuration found for issuer: " + issuer);
        throw new AuthenticationServiceException("No client configuration found for issuer: " + issuer);
      }

      String redirectUri = null;
      if (clientConfig.getRegisteredRedirectUri() != null && clientConfig.getRegisteredRedirectUri().size() == 1) {
        // if there's a redirect uri configured (and only one), use that
        redirectUri = clientConfig.getRegisteredRedirectUri().toArray(new String[] {})[0];
      } else {
        // otherwise our redirect URI is this current URL, with no query parameters
        redirectUri = request.getRequestURL().toString();
      }
      session.setAttribute(REDIRECT_URI_SESION_VARIABLE, redirectUri);
View Full Code Here

    // look up the issuer that we set out to talk to
    String issuer = getStoredSessionString(session, ISSUER_SESSION_VARIABLE);

    // pull the configurations based on that issuer
    ServerConfiguration serverConfig = servers.getServerConfiguration(issuer);
    final RegisteredClient clientConfig = clients.getClientConfiguration(serverConfig);

    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    form.add("grant_type", "authorization_code");
    form.add("code", authorizationCode);

    String redirectUri = getStoredSessionString(session, REDIRECT_URI_SESION_VARIABLE);
    if (redirectUri != null) {
      form.add("redirect_uri", redirectUri);
    }

    // Handle Token Endpoint interaction
    HttpClient httpClient = new SystemDefaultHttpClient();

    httpClient.getParams().setParameter("http.socket.timeout", new Integer(httpSocketTimeout));

    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);

    RestTemplate restTemplate;

    if (SECRET_BASIC.equals(clientConfig.getTokenEndpointAuthMethod())){
      // use BASIC auth if configured to do so
      restTemplate = new RestTemplate(factory) {

        @Override
        protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
          ClientHttpRequest httpRequest = super.createRequest(url, method);
          httpRequest.getHeaders().add("Authorization",
              String.format("Basic %s", Base64.encode(String.format("%s:%s", clientConfig.getClientId(), clientConfig.getClientSecret())) ));



          return httpRequest;
        }
      };
    } else {
      // we're not doing basic auth, figure out what other flavor we have
      restTemplate = new RestTemplate(factory);

      if (SECRET_JWT.equals(clientConfig.getTokenEndpointAuthMethod()) || PRIVATE_KEY.equals(clientConfig.getTokenEndpointAuthMethod())) {
        // do a symmetric secret signed JWT for auth


        JwtSigningAndValidationService signer = null;
        JWSAlgorithm alg = clientConfig.getTokenEndpointAuthSigningAlg();

        if (SECRET_JWT.equals(clientConfig.getTokenEndpointAuthMethod()) &&
            (alg.equals(JWSAlgorithm.HS256)
                || alg.equals(JWSAlgorithm.HS384)
                || alg.equals(JWSAlgorithm.HS512))) {

          // generate one based on client secret
          signer = symmetricCacheService.getSymmetricValidtor(clientConfig.getClient());

        } else if (PRIVATE_KEY.equals(clientConfig.getTokenEndpointAuthMethod())) {

          // needs to be wired in to the bean
          signer = authenticationSignerService;
         
          if (alg == null) {
            alg = authenticationSignerService.getDefaultSigningAlgorithm();
          }
        }

        if (signer == null) {
          throw new AuthenticationServiceException("Couldn't find required signer service for use with private key auth.");
        }

        JWTClaimsSet claimsSet = new JWTClaimsSet();

        claimsSet.setIssuer(clientConfig.getClientId());
        claimsSet.setSubject(clientConfig.getClientId());
        claimsSet.setAudience(Lists.newArrayList(serverConfig.getTokenEndpointUri()));

        // TODO: make this configurable
        Date exp = new Date(System.currentTimeMillis() + (60 * 1000)); // auth good for 60 seconds
        claimsSet.setExpirationTime(exp);

        Date now = new Date(System.currentTimeMillis());
        claimsSet.setIssueTime(now);
        claimsSet.setNotBeforeTime(now);

        SignedJWT jwt = new SignedJWT(new JWSHeader(alg), claimsSet);

        signer.signJwt(jwt, alg);

        form.add("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
        form.add("client_assertion", jwt.serialize());
      } else {
        //Alternatively use form based auth
        form.add("client_id", clientConfig.getClientId());
        form.add("client_secret", clientConfig.getClientSecret());
      }

    }

    logger.debug("tokenEndpointURI = " + serverConfig.getTokenEndpointUri());
    logger.debug("form = " + form);

    String jsonString = null;

    try {
      jsonString = restTemplate.postForObject(serverConfig.getTokenEndpointUri(), form, String.class);
    } catch (HttpClientErrorException httpClientErrorException) {

      // Handle error

      logger.error("Token Endpoint error response:  "
          + httpClientErrorException.getStatusText() + " : "
          + httpClientErrorException.getMessage());

      throw new AuthenticationServiceException("Unable to obtain Access Token: " + httpClientErrorException.getMessage());
    }

    logger.debug("from TokenEndpoint jsonString = " + jsonString);

    JsonElement jsonRoot = new JsonParser().parse(jsonString);
    if (!jsonRoot.isJsonObject()) {
      throw new AuthenticationServiceException("Token Endpoint did not return a JSON object: " + jsonRoot);
    }

    JsonObject tokenResponse = jsonRoot.getAsJsonObject();

    if (tokenResponse.get("error") != null) {

      // Handle error

      String error = tokenResponse.get("error").getAsString();

      logger.error("Token Endpoint returned: " + error);

      throw new AuthenticationServiceException("Unable to obtain Access Token.  Token Endpoint returned: " + error);

    } else {

      // Extract the id_token to insert into the
      // OIDCAuthenticationToken

      // get out all the token strings
      String accessTokenValue = null;
      String idTokenValue = null;
      String refreshTokenValue = null;

      if (tokenResponse.has("access_token")) {
        accessTokenValue = tokenResponse.get("access_token").getAsString();
      } else {
        throw new AuthenticationServiceException("Token Endpoint did not return an access_token: " + jsonString);
      }

      if (tokenResponse.has("id_token")) {
        idTokenValue = tokenResponse.get("id_token").getAsString();
      } else {
        logger.error("Token Endpoint did not return an id_token");
        throw new AuthenticationServiceException("Token Endpoint did not return an id_token");
      }

      if (tokenResponse.has("refresh_token")) {
        refreshTokenValue = tokenResponse.get("refresh_token").getAsString();
      }

      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)) {
View Full Code Here

   * @see org.mitre.openid.connect.client.service.ClientConfigurationService#getClientConfiguration(org.mitre.openid.connect.config.ServerConfiguration)
   */
  @Override
  public RegisteredClient getClientConfiguration(ServerConfiguration issuer) {

    RegisteredClient client = staticClientService.getClientConfiguration(issuer);
    if (client != null) {
      return client;
    } else {
      return dynamicClientService.getClientConfiguration(issuer);
    }
View Full Code Here

        OAuth2AccessTokenEntity token = connectTokenService.createRegistrationAccessToken(savedClient);
        token = tokenService.saveAccessToken(token);

        // send it all out to the view

        RegisteredClient registered = new RegisteredClient(savedClient, token.getValue(), config.getIssuer() + "register/" + UriUtils.encodePathSegment(savedClient.getClientId(), "UTF-8"));
        m.addAttribute("client", registered);
        m.addAttribute("code", HttpStatus.CREATED); // http 201

        return ClientInformationResponseView.VIEWNAME;
      } catch (UnsupportedEncodingException e) {
View Full Code Here

    if (client != null && client.getClientId().equals(auth.getOAuth2Request().getClientId())) {

      try {
        OAuth2AccessTokenEntity token = fetchValidRegistrationToken(auth, client);
        RegisteredClient registered = new RegisteredClient(client, token.getValue(), config.getIssuer() + "register/" +  UriUtils.encodePathSegment(client.getClientId(), "UTF-8"));

        // send it all out to the view
        m.addAttribute("client", registered);
        m.addAttribute("code", HttpStatus.OK); // http 200
View Full Code Here

TOP

Related Classes of org.mitre.oauth2.model.RegisteredClient

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.