Exemplo n.º 1
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;
  }
Exemplo n.º 2
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;
  }