Пример #1
0
  /**
   * {@code APIManagerComponent} calls this method, passing KeyManagerConfiguration as a {@code
   * String}.
   *
   * @param configuration Configuration as a {@link
   *     org.wso2.carbon.apimgt.api.model.KeyManagerConfiguration}
   */
  @Override
  public void loadConfiguration(KeyManagerConfiguration configuration)
      throws APIManagementException {

    this.configuration = configuration;
    LOGGER.log(Level.INFO, "Configuration: " + configuration.toString());
  }
Пример #2
0
  /**
   * Deletes OAuth Client from Authorization Server.
   *
   * @param consumerKey consumer key of the OAuth Client.
   * @throws APIManagementException
   */
  @Override
  public void deleteApplication(String consumerKey) throws APIManagementException {

    LOGGER.log(
        Level.INFO, "OAuthTwoClient - deleteApplication: " + consumerKey + " will be deleted.");

    Long id = nameIdMapping.get(consumerKey);

    String configURL = configuration.getParameter(OAuthTwoConstants.CLIENT_REG_ENDPOINT);
    String configURLsAccessToken =
        configuration.getParameter(OAuthTwoConstants.REGISTRAION_ACCESS_TOKEN);
    HttpClient client = getHttpClient();

    try {

      // Deletion has to be called providing the ID. If we don't have the
      // ID we can't proceed with Delete.
      if (id != null) {
        configURL += "/" + id.toString();
        HttpDelete httpDelete = new HttpDelete(configURL);

        LOGGER.log(
            Level.INFO, "OAuthTwoClient - deleteApplication: id:" + id + " URL:" + configURL);

        // Set Authorization Header
        httpDelete.addHeader(
            OAuthTwoConstants.AUTHORIZATION, OAuthTwoConstants.BEARER + configURLsAccessToken);
        HttpResponse response = client.execute(httpDelete);
        int responseCode = response.getStatusLine().getStatusCode();
        LOGGER.log(Level.INFO, "Delete application response code :  " + responseCode);
        if (responseCode == HttpStatus.SC_OK || responseCode == HttpStatus.SC_NO_CONTENT) {
          LOGGER.log(
              Level.INFO,
              "OAuth Client for consumer Id " + consumerKey + " has been successfully deleted");
          nameIdMapping.remove(consumerKey);
        } else {
          handleException("Problem occurred while deleting client for Consumer Key " + consumerKey);
        }
      }

    } catch (IOException e) {
      handleException("Error while reading response body from Server ", e);
    } finally {
      client.getConnectionManager().shutdown();
    }
  }
Пример #3
0
  /**
   * This method will Register the client in Authorization Server.
   *
   * @param oauthAppRequest this object holds all parameters required to register an OAuth Client.
   */
  @Override
  public OAuthApplicationInfo createApplication(OAuthAppRequest oauthAppRequest)
      throws APIManagementException {

    OAuthApplicationInfo oAuthApplicationInfo = oauthAppRequest.getOAuthApplicationInfo();

    LOGGER.log(Level.INFO, "Creating a new oAuthApp in Authorization Server");
    System.out.println("Creating a new oAuthApp in Authorization Server");

    KeyManagerConfiguration config =
        KeyManagerHolder.getKeyManagerInstance().getKeyManagerConfiguration();

    // Getting Client Registration Url and Access Token from Config.
    String registrationEndpoint = config.getParameter(OAuthTwoConstants.CLIENT_REG_ENDPOINT);
    String registrationToken = config.getParameter(OAuthTwoConstants.REGISTRAION_ACCESS_TOKEN);

    HttpPost httpPost = new HttpPost(registrationEndpoint.trim());

    HttpClient httpClient = getHttpClient();

    BufferedReader reader = null;
    try {
      // Create the JSON Payload that should be sent to OAuth Server.
      String jsonPayload = createJsonPayloadFromOauthApplication(oAuthApplicationInfo);

      LOGGER.log(Level.INFO, "Payload for creating new client : " + jsonPayload);
      System.out.println("Payload for creating new client : " + jsonPayload);

      httpPost.setEntity(new StringEntity(jsonPayload, OAuthTwoConstants.UTF_8));
      httpPost.setHeader(
          OAuthTwoConstants.CONTENT_TYPE, OAuthTwoConstants.APPLICATION_JSON_CONTENT_TYPE);

      // Setting Authorization Header, with Access Token
      httpPost.setHeader(
          OAuthTwoConstants.AUTHORIZATION, OAuthTwoConstants.BEARER + registrationToken);

      HttpResponse response = httpClient.execute(httpPost);
      int responseCode = response.getStatusLine().getStatusCode();

      JSONObject parsedObject;
      HttpEntity entity = response.getEntity();
      reader =
          new BufferedReader(new InputStreamReader(entity.getContent(), OAuthTwoConstants.UTF_8));

      // If successful a 201 will be returned.
      if (HttpStatus.SC_CREATED == responseCode) {

        parsedObject = getParsedObjectByReader(reader);
        if (parsedObject != null) {
          oAuthApplicationInfo = createOAuthAppfromResponse(parsedObject);

          // We need the id when retrieving a single OAuth Client. So
          // we have to maintain a mapping
          // between the consumer key and the ID.
          LOGGER.log(
              Level.INFO,
              "OAuthClient - Mapping | ClientId:"
                  + oAuthApplicationInfo.getClientId()
                  + " > Id:"
                  + oAuthApplicationInfo.getParameter("id"));
          nameIdMapping.put(
              oAuthApplicationInfo.getClientId(), (Long) oAuthApplicationInfo.getParameter("id"));

          return oAuthApplicationInfo;
        }
      } else {
        handleException(
            "Some thing wrong here while registering the new client "
                + "HTTP Error response code is "
                + responseCode);
      }

    } catch (UnsupportedEncodingException e) {
      handleException("Encoding for the Response not-supported.", e);
    } catch (ParseException e) {
      handleException("Error while parsing response json", e);
    } catch (IOException e) {
      handleException("Error while reading response body ", e);
    } finally {
      // close buffer reader.
      if (reader != null) {
        IOUtils.closeQuietly(reader);
      }
      httpClient.getConnectionManager().shutdown();
    }
    return null;
  }
Пример #4
0
  @Override
  public AccessTokenInfo getTokenMetaData(String accessToken) throws APIManagementException {
    AccessTokenInfo tokenInfo = new AccessTokenInfo();

    KeyManagerConfiguration config =
        KeyManagerHolder.getKeyManagerInstance().getKeyManagerConfiguration();

    String introspectionURL = config.getParameter(OAuthTwoConstants.INTROSPECTION_URL);
    String introspectionConsumerKey = config.getParameter(OAuthTwoConstants.INTROSPECTION_CK);
    String introspectionConsumerSecret = config.getParameter(OAuthTwoConstants.INTROSPECTION_CS);
    String encodedSecret =
        Base64.encode(
            new String(introspectionConsumerKey + ":" + introspectionConsumerSecret).getBytes());

    BufferedReader reader = null;

    try {
      URIBuilder uriBuilder = new URIBuilder(introspectionURL);
      uriBuilder.addParameter("access_token", accessToken);
      uriBuilder.build();

      HttpGet httpGet = new HttpGet(uriBuilder.build());
      HttpClient client = new DefaultHttpClient();

      httpGet.setHeader("Authorization", "Basic " + encodedSecret);
      HttpResponse response = client.execute(httpGet);
      int responseCode = response.getStatusLine().getStatusCode();

      LOGGER.log(Level.INFO, "HTTP Response code : " + responseCode);

      // {"audience":"MappedClient","scopes":["test"],"principal":{"name":"mappedclient","roles":[],"groups":[],"adminPrincipal":false,
      // "attributes":{}},"expires_in":1433059160531}
      HttpEntity entity = response.getEntity();
      JSONObject parsedObject;
      String errorMessage = null;
      reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));

      if (HttpStatus.SC_OK == responseCode) {
        // pass bufferReader object and get read it and retrieve the
        // parsedJson object
        parsedObject = getParsedObjectByReader(reader);
        if (parsedObject != null) {

          Map valueMap = parsedObject;
          Object principal = valueMap.get("principal");

          if (principal == null) {
            tokenInfo.setTokenValid(false);
            return tokenInfo;
          }
          Map principalMap = (Map) principal;
          String clientId = (String) principalMap.get("clientId");
          Long expiryTimeString = (Long) valueMap.get("expires_in");
          String endUserName = (String) principalMap.get("name");

          LOGGER.log(
              Level.INFO,
              "OAuthTwoClient - clientId:" + clientId + " expires_in:" + expiryTimeString);

          // Returning false if mandatory attributes are missing.
          if (clientId == null || expiryTimeString == null) {
            tokenInfo.setTokenValid(false);
            tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_EXPIRED);
            return tokenInfo;
          }

          long currentTime = System.currentTimeMillis();
          long expiryTime = expiryTimeString;
          if (expiryTime > currentTime) {
            tokenInfo.setTokenValid(true);
            tokenInfo.setConsumerKey(clientId);
            tokenInfo.setValidityPeriod(expiryTime - currentTime);
            // Considering Current Time as the issued time.
            tokenInfo.setIssuedTime(currentTime);
            tokenInfo.setEndUserName(endUserName);
            tokenInfo.setAccessToken(accessToken);
            //			tokenInfo.

            JSONArray scopesArray = (JSONArray) valueMap.get("scopes");

            if (scopesArray != null && !scopesArray.isEmpty()) {

              String[] scopes = new String[scopesArray.size()];
              for (int i = 0; i < scopes.length; i++) {
                scopes[i] = (String) scopesArray.get(i);
              }
              tokenInfo.setScope(scopes);
            }
          } else {
            tokenInfo.setTokenValid(false);
            tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE);
            return tokenInfo;
          }

        } else {
          LOGGER.log(Level.SEVERE, "Invalid Token " + accessToken);
          tokenInfo.setTokenValid(false);
          tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE);
          return tokenInfo;
        }
      } // for other HTTP error codes we just pass generic message.
      else {
        LOGGER.log(Level.SEVERE, "Invalid Token " + accessToken);
        tokenInfo.setTokenValid(false);
        tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE);
        return tokenInfo;
      }

    } catch (UnsupportedEncodingException e) {
      handleException("The Character Encoding is not supported. " + e.getMessage(), e);
    } catch (ClientProtocolException e) {
      handleException(
          "HTTP request error has occurred while sending request  to OAuth Provider. "
              + e.getMessage(),
          e);
    } catch (IOException e) {
      handleException(
          "Error has occurred while reading or closing buffer reader. " + e.getMessage(), e);
    } catch (URISyntaxException e) {
      handleException("Error occurred while building URL with params." + e.getMessage(), e);
    } catch (ParseException e) {
      handleException("Error while parsing response json " + e.getMessage(), e);
    } finally {
      IOUtils.closeQuietly(reader);
    }
    LOGGER.log(
        Level.INFO,
        "OAuthTwoClient - getTokenMetada - return SUCCESSFULY" + tokenInfo.getJSONString());

    return tokenInfo;
  }
Пример #5
0
  /**
   * This method retrieves OAuth application details by given consumer key.
   *
   * @param consumerKey consumer key of the OAuth Client.
   * @return an {@code OAuthApplicationInfo} having all the details of an OAuth Client.
   * @throws APIManagementException
   */
  @Override
  public OAuthApplicationInfo retrieveApplication(String consumerKey)
      throws APIManagementException {

    HttpClient client = getHttpClient();

    // First get the Id corresponding to consumerKey
    Long id = nameIdMapping.get(consumerKey);
    String registrationURL = configuration.getParameter(OAuthTwoConstants.CLIENT_REG_ENDPOINT);
    String accessToken = configuration.getParameter(OAuthTwoConstants.REGISTRAION_ACCESS_TOKEN);
    BufferedReader reader = null;

    try {

      if (id != null) {
        // To get the specific client, we have to call like
        // http://192.168.52.5:8080/admin/resourceServer/251/client/355
        LOGGER.log(Level.INFO, "Found id : " + id.toString() + " for consumer key :" + consumerKey);
        registrationURL += "/" + id.toString();
      }

      HttpGet request = new HttpGet(registrationURL);
      // set authorization header.
      request.addHeader(OAuthTwoConstants.AUTHORIZATION, OAuthTwoConstants.BEARER + accessToken);
      HttpResponse response = client.execute(request);

      int responseCode = response.getStatusLine().getStatusCode();
      Object parsedObject;

      HttpEntity entity = response.getEntity();

      reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));

      if (responseCode == HttpStatus.SC_CREATED || responseCode == HttpStatus.SC_OK) {
        JSONParser parser = new JSONParser();
        if (reader != null) {
          parsedObject = parser.parse(reader);

          // If we have appended the ID, then the response is a
          // JSONObject if not the response is a JSONArray.
          if (parsedObject instanceof JSONArray) {
            // If the response is a JSONArray, then we prime the
            // nameId map,
            // with the response received. And then return details
            // of the specific client.
            addToNameIdMap((JSONArray) parsedObject);
            for (Object object : (JSONArray) parsedObject) {
              JSONObject jsonObject = (JSONObject) object;
              if ((jsonObject.get(OAuthTwoConstants.CLIENT_ID)).equals(consumerKey)) {
                return createOAuthAppfromResponse(jsonObject);
              }
            }
          } else {
            return createOAuthAppfromResponse((JSONObject) parsedObject);
          }
        }

      } else {
        handleException(
            "Something went wrong while retrieving client for consumer key " + consumerKey);
      }

    } catch (ParseException e) {
      handleException("Error while parsing response json.", e);
    } catch (IOException e) {
      handleException("Error while reading response body.", e);
    } finally {
      client.getConnectionManager().shutdown();
      IOUtils.closeQuietly(reader);
    }

    return null;
  }
Пример #6
0
  /**
   * This method will update an existing OAuth Client.
   *
   * @param oauthAppRequest Parameters to be passed to Authorization Server, encapsulated as an
   *     {@code OAuthAppRequest}
   * @return Details of updated OAuth Client.
   * @throws APIManagementException
   */
  @Override
  public OAuthApplicationInfo updateApplication(OAuthAppRequest oauthAppRequest)
      throws APIManagementException {

    LOGGER.log(Level.INFO, "Updating OAuth Client..");

    // We have to send the id with the update request.
    String consumerKey = oauthAppRequest.getOAuthApplicationInfo().getClientId();

    Long id = nameIdMapping.get(consumerKey);

    if (id == null) {
      return oauthAppRequest.getOAuthApplicationInfo();
    }

    String registrationUrl = configuration.getParameter(OAuthTwoConstants.CLIENT_REG_ENDPOINT);
    String accessToken = configuration.getParameter(OAuthTwoConstants.REGISTRAION_ACCESS_TOKEN);
    BufferedReader reader = null;
    oauthAppRequest.getOAuthApplicationInfo().addParameter("id", id);

    registrationUrl += "/" + id.toString();

    HttpClient client = getHttpClient();
    try {
      String jsonPayload =
          createJsonPayloadFromOauthApplication(oauthAppRequest.getOAuthApplicationInfo());

      LOGGER.log(Level.INFO, "JSON Payload for update method : " + jsonPayload);

      HttpPost httpPost = new HttpPost(registrationUrl);
      httpPost.setEntity(new StringEntity(jsonPayload, "UTF8"));
      httpPost.setHeader(
          OAuthTwoConstants.CONTENT_TYPE, OAuthTwoConstants.APPLICATION_JSON_CONTENT_TYPE);
      httpPost.setHeader(OAuthTwoConstants.AUTHORIZATION, OAuthTwoConstants.BEARER + accessToken);
      HttpResponse response = client.execute(httpPost);

      int responseCode = response.getStatusLine().getStatusCode();

      LOGGER.log(Level.INFO, "Response Code from Server: " + responseCode);

      JSONObject parsedObject;

      HttpEntity entity = response.getEntity();
      reader =
          new BufferedReader(new InputStreamReader(entity.getContent(), OAuthTwoConstants.UTF_8));

      if (responseCode == HttpStatus.SC_CREATED || responseCode == HttpStatus.SC_OK) {
        parsedObject = getParsedObjectByReader(reader);
        if (parsedObject != null) {
          return createOAuthAppfromResponse(parsedObject);
        } else {
          handleException("ParseObject is empty. Can not return oAuthApplicationInfo.");
        }
      } else {
        handleException(
            "Some thing wrong here when updating the Client for key."
                + oauthAppRequest.getOAuthApplicationInfo().getClientId()
                + ". Error "
                + "code"
                + responseCode);
      }

    } catch (UnsupportedEncodingException e) {
      handleException(
          "Some thing wrong here when Updating a Client for key "
              + oauthAppRequest.getOAuthApplicationInfo().getClientId(),
          e);
    } catch (ParseException e) {
      handleException("Error while parsing response json", e);
    } catch (IOException e) {
      handleException("Error while reading response body from Server ", e);
    } finally {
      if (reader != null) {
        IOUtils.closeQuietly(reader);
      }
      client.getConnectionManager().shutdown();
    }
    return null;
  }