Esempio n. 1
0
  public void updateConsumerApplication(OAuthAppDO oauthAppDO) throws IdentityOAuthAdminException {
    Connection connection = null;
    PreparedStatement prepStmt = null;

    try {
      connection = JDBCPersistenceManager.getInstance().getDBConnection();
      prepStmt = connection.prepareStatement(SQLQueries.OAuthAppDAOSQLQueries.UPDATE_CONSUMER_APP);
      prepStmt.setString(1, oauthAppDO.getApplicationName());
      prepStmt.setString(2, oauthAppDO.getCallbackUrl());
      prepStmt.setString(3, oauthAppDO.getGrantTypes());
      prepStmt.setString(
          4, tokenPersistenceProcessor.getProcessedToken(oauthAppDO.getOauthConsumerKey()));
      prepStmt.setString(
          5, tokenPersistenceProcessor.getProcessedToken(oauthAppDO.getOauthConsumerSecret()));

      int count = prepStmt.executeUpdate();
      if (log.isDebugEnabled()) {
        log.debug("No. of records updated for updating consumer application. : " + count);
      }
      connection.commit();

    } catch (IdentityException e) {
      String errorMsg = "Error when getting an Identity Persistence Store instance.";
      log.error(errorMsg, e);
      throw new IdentityOAuthAdminException(errorMsg, e);
    } catch (SQLException e) {
      log.error(
          "Error when executing the SQL : " + SQLQueries.OAuthAppDAOSQLQueries.UPDATE_CONSUMER_APP);
      log.error(e.getMessage(), e);
      throw new IdentityOAuthAdminException("Error updating the consumer application.");
    } finally {
      IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt);
    }
  }
Esempio n. 2
0
  public OAuthAppDO getAppInformation(String consumerKey)
      throws InvalidOAuthClientException, IdentityOAuth2Exception {
    Connection connection = null;
    PreparedStatement prepStmt = null;
    ResultSet rSet = null;
    OAuthAppDO oauthApp = null;

    try {
      connection = JDBCPersistenceManager.getInstance().getDBConnection();
      prepStmt = connection.prepareStatement(SQLQueries.OAuthAppDAOSQLQueries.GET_APP_INFO);
      prepStmt.setString(1, tokenPersistenceProcessor.getProcessedToken(consumerKey));

      rSet = prepStmt.executeQuery();
      List<OAuthAppDO> oauthApps = new ArrayList<OAuthAppDO>();
      /**
       * We need to determine whether the result set has more than 1 row. Meaning, we found an
       * application for the given consumer key. There can be situations where a user passed a key
       * which doesn't yet have an associated application. We need to barf with a meaningful error
       * message for this case
       */
      boolean rSetHasRows = false;
      while (rSet.next()) {
        // There is at least one application associated with a given key
        rSetHasRows = true;
        if (rSet.getString(4) != null && rSet.getString(4).length() > 0) {
          oauthApp = new OAuthAppDO();
          oauthApp.setOauthConsumerKey(consumerKey);
          oauthApp.setOauthConsumerSecret(
              tokenPersistenceProcessor.getPreprocessedToken(rSet.getString(1)));
          oauthApp.setUserName(rSet.getString(2));
          oauthApp.setApplicationName(rSet.getString(3));
          oauthApp.setOauthVersion(rSet.getString(4));
          oauthApp.setCallbackUrl(rSet.getString(5));
          oauthApp.setTenantId(rSet.getInt(6));
          oauthApp.setGrantTypes(rSet.getString(7));
          oauthApps.add(oauthApp);
        }
      }
      if (!rSetHasRows) {
        /**
         * We come here because user submitted a key that doesn't have any associated application
         * with it. We're throwing an error here because we cannot continue without this info.
         * Otherwise it'll throw a null values not supported error when it tries to cache this info
         */
        String message =
            "Cannot find an application associated with the given consumer key : " + consumerKey;
        log.debug(message);
        throw new InvalidOAuthClientException(message);
      }
    } catch (IdentityException e) {
      log.debug(e.getMessage(), e);
      throw new IdentityOAuth2Exception(e.getMessage());
    } catch (SQLException e) {
      log.debug(e.getMessage(), e);
      throw new IdentityOAuth2Exception(e.getMessage());
    } finally {
      IdentityDatabaseUtil.closeAllConnections(connection, rSet, prepStmt);
    }
    return oauthApp;
  }
Esempio n. 3
0
  public void addOAuthApplication(OAuthAppDO consumerAppDO) throws IdentityOAuthAdminException {
    Connection connection = null;
    PreparedStatement prepStmt = null;

    if (!isDuplicateApplication(
        consumerAppDO.getUserName(), consumerAppDO.getTenantId(), consumerAppDO)) {
      try {
        connection = JDBCPersistenceManager.getInstance().getDBConnection();
        prepStmt = connection.prepareStatement(SQLQueries.OAuthAppDAOSQLQueries.ADD_OAUTH_APP);
        prepStmt.setString(
            1, tokenPersistenceProcessor.getProcessedToken(consumerAppDO.getOauthConsumerKey()));
        prepStmt.setString(
            2, tokenPersistenceProcessor.getProcessedToken(consumerAppDO.getOauthConsumerSecret()));
        prepStmt.setString(3, consumerAppDO.getUserName());
        prepStmt.setInt(4, consumerAppDO.getTenantId());
        prepStmt.setString(5, consumerAppDO.getApplicationName());
        prepStmt.setString(6, consumerAppDO.getOauthVersion());
        prepStmt.setString(7, consumerAppDO.getCallbackUrl());
        prepStmt.setString(8, consumerAppDO.getGrantTypes());
        prepStmt.execute();
        connection.commit();

      } catch (IdentityException e) {
        String errorMsg = "Error when getting an Identity Persistence Store instance.";
        log.error(errorMsg, e);
        throw new IdentityOAuthAdminException(errorMsg, e);
      } catch (SQLException e) {
        log.error(
            "Error when executing the SQL : " + SQLQueries.OAuthAppDAOSQLQueries.ADD_OAUTH_APP);
        log.error(e.getMessage(), e);
        throw new IdentityOAuthAdminException(
            "Error when adding a new OAuth consumer application.");
      } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt);
      }
    } else {
      throw new IdentityOAuthAdminException(
          "Error when adding the consumer application. "
              + "An application with the same name already exists.");
    }
  }
Esempio n. 4
0
  public OAuthAppDO[] getOAuthConsumerAppsOfUser(String username, int tenantId)
      throws IdentityOAuthAdminException {
    Connection connection = null;
    PreparedStatement prepStmt = null;
    ResultSet rSet = null;
    OAuthAppDO[] oauthAppsOfUser;
    try {
      connection = JDBCPersistenceManager.getInstance().getDBConnection();
      prepStmt = connection.prepareStatement(SQLQueries.OAuthAppDAOSQLQueries.GET_APPS_OF_USER);
      prepStmt.setString(1, username);
      prepStmt.setInt(2, tenantId);

      rSet = prepStmt.executeQuery();
      List<OAuthAppDO> oauthApps = new ArrayList<OAuthAppDO>();
      while (rSet.next()) {
        if (rSet.getString(3) != null && rSet.getString(3).length() > 0) {
          OAuthAppDO oauthApp = new OAuthAppDO();
          oauthApp.setUserName(username);
          oauthApp.setTenantId(tenantId);
          oauthApp.setOauthConsumerKey(
              tokenPersistenceProcessor.getPreprocessedToken(rSet.getString(1)));
          oauthApp.setOauthConsumerSecret(
              tokenPersistenceProcessor.getPreprocessedToken(rSet.getString(2)));
          oauthApp.setApplicationName(rSet.getString(3));
          oauthApp.setOauthVersion(rSet.getString(4));
          oauthApp.setCallbackUrl(rSet.getString(5));
          oauthApp.setGrantTypes(rSet.getString(6));
          oauthApps.add(oauthApp);
        }
      }
      oauthAppsOfUser = oauthApps.toArray(new OAuthAppDO[oauthApps.size()]);
    } catch (IdentityException e) {
      String errorMsg = "Error when getting an Identity Persistence Store instance.";
      log.error(errorMsg, e);
      throw new IdentityOAuthAdminException(errorMsg, e);
    } catch (SQLException e) {
      log.error(
          "Error when executing the SQL : " + SQLQueries.OAuthAppDAOSQLQueries.GET_APPS_OF_USER);
      log.error(e.getMessage(), e);
      throw new IdentityOAuthAdminException(
          "Error when reading the application information from the persistence store.");
    } finally {
      IdentityDatabaseUtil.closeAllConnections(connection, rSet, prepStmt);
    }
    return oauthAppsOfUser;
  }
Esempio n. 5
0
  private boolean isDuplicateApplication(String username, int tenantId, OAuthAppDO consumerAppDTO)
      throws IdentityOAuthAdminException {
    Connection connection = null;
    PreparedStatement prepStmt = null;
    ResultSet rSet = null;

    boolean isDuplicateApp = false;

    try {
      connection = JDBCPersistenceManager.getInstance().getDBConnection();
      prepStmt =
          connection.prepareStatement(SQLQueries.OAuthAppDAOSQLQueries.CHECK_EXISTING_APPLICATION);
      prepStmt.setString(1, username);
      prepStmt.setInt(2, tenantId);
      prepStmt.setString(3, consumerAppDTO.getApplicationName());

      rSet = prepStmt.executeQuery();
      if (rSet.next()) {
        isDuplicateApp = true;
      }
    } catch (IdentityException e) {
      String errorMsg = "Error when getting an Identity Persistence Store instance.";
      log.error(errorMsg, e);
      throw new IdentityOAuthAdminException(errorMsg, e);
    } catch (SQLException e) {
      log.error(
          "Error when executing the SQL : "
              + SQLQueries.OAuthAppDAOSQLQueries.CHECK_EXISTING_APPLICATION);
      log.error(e.getMessage(), e);
      throw new IdentityOAuthAdminException(
          "Error when reading the application information from the persistence store.");
    } finally {
      IdentityDatabaseUtil.closeAllConnections(connection, rSet, prepStmt);
    }
    return isDuplicateApp;
  }
  public OAuth2AccessTokenRespDTO issue(OAuth2AccessTokenReqDTO tokenReqDTO)
      throws IdentityException, InvalidOAuthClientException {

    String grantType = tokenReqDTO.getGrantType();
    OAuth2AccessTokenRespDTO tokenRespDTO;

    AuthorizationGrantHandler authzGrantHandler = authzGrantHandlers.get(grantType);

    OAuthTokenReqMessageContext tokReqMsgCtx = new OAuthTokenReqMessageContext(tokenReqDTO);

    // If multiple client authentication methods have been used the authorization server must reject
    // the request
    int authenticatorHandlerIndex = -1;
    for (int i = 0; i < clientAuthenticationHandlers.size(); i++) {
      if (clientAuthenticationHandlers.get(i).canAuthenticate(tokReqMsgCtx)) {
        if (authenticatorHandlerIndex > -1) {
          log.debug(
              "Multiple Client Authentication Methods used for client id : "
                  + tokenReqDTO.getClientId());
          tokenRespDTO =
              handleError(
                  OAuthConstants.OAuthError.TokenResponse.UNSUPPORTED_CLIENT_AUTHENTICATION_METHOD,
                  "Unsupported Client Authentication Method!",
                  tokenReqDTO);
          setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
          return tokenRespDTO;
        }
        authenticatorHandlerIndex = i;
      }
    }
    if (authenticatorHandlerIndex < 0 && authzGrantHandler.isConfidentialClient()) {
      log.debug(
          "Confidential client cannot be authenticated for client id : "
              + tokenReqDTO.getClientId());
      tokenRespDTO =
          handleError(
              OAuthConstants.OAuthError.TokenResponse.UNSUPPORTED_CLIENT_AUTHENTICATION_METHOD,
              "Unsupported Client Authentication Method!",
              tokenReqDTO);
      setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
      return tokenRespDTO;
    }

    ClientAuthenticationHandler clientAuthHandler = null;
    if (authenticatorHandlerIndex > -1) {
      clientAuthHandler = clientAuthenticationHandlers.get(authenticatorHandlerIndex);
    }
    boolean isAuthenticated;
    if (clientAuthHandler != null) {
      isAuthenticated = clientAuthHandler.authenticateClient(tokReqMsgCtx);
    } else {
      isAuthenticated = true;
    }
    if (!isAuthenticated) {
      if (log.isDebugEnabled()) {
        log.debug("Client Authentication failed for client Id: " + tokenReqDTO.getClientId());
      }
      tokenRespDTO =
          handleError(
              OAuthError.TokenResponse.INVALID_CLIENT,
              "Client credentials are invalid.",
              tokenReqDTO);
      setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
      return tokenRespDTO;
    }

    // loading the stored application data
    OAuthAppDO oAuthAppDO = getAppInformation(tokenReqDTO);
    if (!authzGrantHandler.isOfTypeApplicationUser()) {
      tokReqMsgCtx.setAuthorizedUser(OAuth2Util.getUserFromUserName(oAuthAppDO.getUserName()));
      tokReqMsgCtx
          .getAuthorizedUser()
          .setTenantDomain(IdentityTenantUtil.getTenantDomain(oAuthAppDO.getTenantId()));
    }

    boolean isValidGrant = false;
    String error = "Provided Authorization Grant is invalid";
    try {
      isValidGrant = authzGrantHandler.validateGrant(tokReqMsgCtx);
    } catch (IdentityOAuth2Exception e) {
      if (log.isDebugEnabled()) {
        log.debug("Error occurred while validating grant", e);
      }
      error = e.getMessage();
    }

    if (!isValidGrant) {
      if (log.isDebugEnabled()) {
        log.debug("Invalid Grant provided by the client Id: " + tokenReqDTO.getClientId());
      }
      tokenRespDTO = handleError(OAuthError.TokenResponse.INVALID_GRANT, error, tokenReqDTO);
      setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
      return tokenRespDTO;
    }

    boolean isAuthorized = authzGrantHandler.authorizeAccessDelegation(tokReqMsgCtx);
    if (!isAuthorized) {
      if (log.isDebugEnabled()) {
        log.debug("Invalid authorization for client Id = " + tokenReqDTO.getClientId());
      }
      tokenRespDTO =
          handleError(
              OAuthError.TokenResponse.UNAUTHORIZED_CLIENT, "Unauthorized Client!", tokenReqDTO);
      setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
      return tokenRespDTO;
    }

    boolean isValidScope = authzGrantHandler.validateScope(tokReqMsgCtx);
    if (!isValidScope) {
      if (log.isDebugEnabled()) {
        log.debug("Invalid scope provided by client Id: " + tokenReqDTO.getClientId());
      }
      tokenRespDTO =
          handleError(OAuthError.TokenResponse.INVALID_SCOPE, "Invalid Scope!", tokenReqDTO);
      setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
      return tokenRespDTO;
    }

    try {
      // set the token request context to be used by downstream handlers. This is introduced as a
      // fix for
      // IDENTITY-4111.
      OAuth2Util.setTokenRequestContext(tokReqMsgCtx);
      tokenRespDTO = authzGrantHandler.issue(tokReqMsgCtx);
    } finally {
      // clears the token request context.
      OAuth2Util.clearTokenRequestContext();
    }

    tokenRespDTO.setCallbackURI(oAuthAppDO.getCallbackUrl());

    String[] scopes = tokReqMsgCtx.getScope();
    if (scopes != null && scopes.length > 0) {
      StringBuilder scopeString = new StringBuilder("");
      for (String scope : scopes) {
        scopeString.append(scope);
        scopeString.append(" ");
      }
      tokenRespDTO.setAuthorizedScopes(scopeString.toString().trim());
    }

    setResponseHeaders(tokReqMsgCtx, tokenRespDTO);

    // Do not change this log format as these logs use by external applications
    if (log.isDebugEnabled()) {
      log.debug(
          "Access token issued to client Id: "
              + tokenReqDTO.getClientId()
              + " username: "******" and scopes: "
              + tokenRespDTO.getAuthorizedScopes());
    }

    if (tokReqMsgCtx.getScope() != null && OAuth2Util.isOIDCAuthzRequest(tokReqMsgCtx.getScope())) {
      IDTokenBuilder builder =
          OAuthServerConfiguration.getInstance().getOpenIDConnectIDTokenBuilder();
      tokenRespDTO.setIDToken(builder.buildIDToken(tokReqMsgCtx, tokenRespDTO));
    }

    if (tokenReqDTO.getGrantType().equals(GrantType.AUTHORIZATION_CODE.toString())) {
      addUserAttributesToCache(tokenReqDTO, tokenRespDTO);
    }

    return tokenRespDTO;
  }