org.springframework.security.access.AuthorizationServiceException Java Examples

The following examples show how to use org.springframework.security.access.AuthorizationServiceException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RibbonRetryErrorCheckTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
private static Stream<Arguments> provideExceptionsWithRelevantTexts() {
    return Stream.of(
        Arguments.of("givenExceptionChain_whenIsAbortException_thenRequestAbortedGeneric",
            new RequestAbortException("test"),
            "The request to the URL 'null' has been aborted without retrying on another instance. Caused by: org.zowe.apiml.gateway.ribbon.http.RequestAbortException: test",
            "org.zowe.apiml.gateway.requestAborted"),
        Arguments.of("givenExceptionChain_whenIsAbortExceptionWithCause_thenRequestAbortedGenericAndCause",
            new RequestAbortException(new AuthorizationServiceException("test")),
            "The request to the URL 'null' has been aborted without retrying on another instance. Caused by: org.zowe.apiml.gateway.ribbon.http.RequestAbortException: org.springframework.security.access.AuthorizationServiceException: test, Caused by: org.springframework.security.access.AuthorizationServiceException: test",
            "org.zowe.apiml.gateway.requestAborted"),
        Arguments.of("givenExceptionChainWithTwoNestedExceptions_whenIsAbortExceptionWithCause_thenRequestAbortedGenericAndCause",
            new RequestAbortException(new AuthorizationServiceException("msg", new BadCredentialsException("test"))),
            "The request to the URL 'null' has been aborted without retrying on another instance. Caused by: org.zowe.apiml.gateway.ribbon.http.RequestAbortException: org.springframework.security.access.AuthorizationServiceException: msg, Caused by: org.springframework.security.access.AuthorizationServiceException: msg, Caused by: org.springframework.security.authentication.BadCredentialsException: test",
            "org.zowe.apiml.gateway.requestAborted"),
        Arguments.of("givenExceptionChain_whenIsContextNotPreparedExceptionWithCause_thenContextNotPreparedAndCause",
            new RequestContextNotPreparedException("RequestContext not prepared for load balancing."),
            "RequestContext not prepared for load balancing.",
            "org.zowe.apiml.gateway.contextNotPrepared"),
        Arguments.of("givenExceptionChain_whenIsConnectionException_thenConnectionExceptionAndCause",
            new ConnectException("test"),
            "The request to the URL 'null' has failed after retrying on all known service instances. Caused by: null",
            "org.zowe.apiml.gateway.connectionRefused")
    );
}
 
Example #2
Source File: SecretsService.java    From guardedbox with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Finds a Secret by secretId and checks if it exists and belongs to an ownerAccountId.
 *
 * @param secretId The secretId.
 * @param ownerAccountId The accountId.
 * @return The Secret.
 */
protected SecretEntity findAndCheckSecret(
        UUID secretId,
        UUID ownerAccountId) {

    SecretEntity secret = secretsRepository.findById(secretId).orElse(null);

    if (secret == null) {
        throw new ServiceException(String.format("Secret %s does not exist", secretId))
                .setErrorCode("my-secrets.secret-does-not-exist");
    }

    if (ownerAccountId != null && !ownerAccountId.equals(secret.getOwnerAccount().getAccountId())) {
        throw new AuthorizationServiceException(String.format(
                "Secret %s cannot be managed by account %s since it belongs to account %s",
                secretId, ownerAccountId, secret.getOwnerAccount().getAccountId()));
    }

    return secret;

}
 
Example #3
Source File: ControllerAdviceConfig.java    From guardedbox with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Exception handler for AuthorizationServiceException.
 *
 * @param e The AuthorizationServiceException.
 * @return Forbidden (403) with no body.
 */
@ExceptionHandler
public ResponseEntity<?> exceptionHandler(
        AuthorizationServiceException e) {

    log.error(String.format(
            "Error during the request %s %s",
            request.getMethod(),
            request.getRequestURI()),
            e);

    session.invalidate();

    return new ResponseEntity<>(HttpStatus.FORBIDDEN);

}
 
Example #4
Source File: Authz.java    From secrets-proxy with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if {@link OneOpsUser} is authorized to manage secrets for the given application group.
 * Env nspath is used as the application group with the <b>{org}_{assembly}_{env}</b> format.
 *
 * @param appName Application name.
 * @param user Authenticated user.
 * @return <code>true</code> if the user is authorized.
 */
public boolean isAuthorized(@Nonnull String appName, @Nonnull OneOpsUser user) throws Exception {
  if (log.isDebugEnabled()) {
    log.debug(
        "Checking the authz for user: "
            + user.getUsername()
            + ", domain: "
            + user.getDomain()
            + " and application: "
            + appName);
  }
  AppGroup appGroup = new AppGroup(user.getDomain(), appName);
  Client client = clientSelector.selectClient(appGroup, userRepo);
  if (client != null && client.authorizeUser(appName, user)) {
    log.info("Authorization process is done for user " + user.getUsername());
  } else {
    throw new AuthorizationServiceException(
        "User '"
            + user.getCn()
            + "' is not a '"
            + SECRETS_ADMIN_TEAM
            + "' or not authorized to manage the secrets for environment: "
            + appGroup.getName());
  }
  return true;
}
 
Example #5
Source File: OneopsClient.java    From secrets-proxy with Apache License 2.0 6 votes vote down vote up
/**
 * Check in UserRepository if user has authorized access for oneops applicaton.
 *
 * @param appName appName
 * @param user OneopsUser
 * @return <code>true</code> if user has admin access.
 */
@Override
public boolean authorizeUser(@Nonnull String appName, @Nonnull OneOpsUser user) {

  AppGroup appGroup = new AppGroup(user.getDomain(), appName);

  List<OneOpsTeam> teams = userRepo.getTeams(user.getUsername(), appGroup);
  boolean hasAccess = teams.stream().anyMatch(team -> hasAdminAccess(team, appGroup));
  if (!hasAccess) {
    throw new AuthorizationServiceException(
        "OneOps user '"
            + user.getCn()
            + "' is not a '"
            + SECRETS_ADMIN_TEAM
            + "' or not authorized to manage the secrets for environment: "
            + appGroup.getNsPath());
  }

  return true;
}
 
Example #6
Source File: GroupsService.java    From guardedbox with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Finds a Group by groupId and checks if it exists and belongs to an accountId.
 *
 * @param groupId The groupId.
 * @param accountId The accountId.
 * @param participantAllowed If this parameter is set to true, the method will check if the accountId owns the group or is a participant.
 * @return The Group.
 */
protected GroupEntity findAndCheckGroup(
        UUID groupId,
        UUID accountId,
        boolean participantAllowed) {

    GroupEntity group = groupsRepository.findById(groupId).orElse(null);

    if (group == null) {
        throw new ServiceException(String.format("Group %s does not exist", groupId))
                .setErrorCode("groups.group-does-not-exist");
    }

    if (accountId != null) {
        if (!accountId.equals(group.getOwnerAccount().getAccountId())) {
            boolean allowedBecauseParticipant = false;
            if (participantAllowed) {
                for (GroupParticipantEntity participant : group.getParticipants()) {
                    if (accountId.equals(participant.getAccount().getAccountId())) {
                        allowedBecauseParticipant = true;
                        break;
                    }
                }
            }
            if (!allowedBecauseParticipant) {
                throw new AuthorizationServiceException(String.format(
                        "Group %s cannot be managed by account %s", groupId, accountId));
            }
        }
    }

    return group;

}
 
Example #7
Source File: TokenProviderUtility.java    From Insights with Apache License 2.0 5 votes vote down vote up
/**
 * Used to verify received token with cached token
 * 
 * @param token
 * @return
 * @throws AuthorizationServiceException
 * @throws AuthenticationCredentialsNotFoundException
 * @throws AccountExpiredException
 * @throws InsightsCustomException
 */
public boolean verifyToken(String token) throws AuthorizationServiceException,
		AuthenticationCredentialsNotFoundException, AccountExpiredException, InsightsCustomException {
	boolean isVerify = Boolean.FALSE;
	boolean isTokenExistsInCache = Boolean.FALSE;
	boolean validateTokenDate = Boolean.FALSE;
	//log.debug(" In verifyToken ");
	try {
		String authToken = ValidationUtils.cleanXSS(token);
		if (authToken == null || authToken.isEmpty()) {
			log.error("authToken is null or empty");
			throw new InsightsCustomException("authToken is null or empty");
		}

		// parse the JWS and verify its HMAC
		SignedJWT signedJWT = SignedJWT.parse(authToken);
		JWSVerifier verifier = new MACVerifier(signingKey);
		isVerify = signedJWT.verify(verifier);

		String id = signedJWT.getJWTClaimsSet().getJWTID();
		String tokenValueFromCache = null;
		if (TokenProviderUtility.tokenCache != null) {
			tokenValueFromCache = TokenProviderUtility.tokenCache.get(id);
		} else {
			log.error("cache is not initilize properly");
		}

		if (tokenValueFromCache == null) {
			log.debug("No token found in cache");
		} else if (tokenValueFromCache.equalsIgnoreCase(authToken)) {
			//log.debug("Token value matched in cache === ");
			isTokenExistsInCache = Boolean.TRUE;
		} else {
			log.error("Token value not matched in cache=== ");
		}

		//log.debug("alice  after " + signedJWT.getJWTClaimsSet().getSubject());
		//log.debug("cognizant.com  " + signedJWT.getJWTClaimsSet().getIssuer());
		//log.debug("Exceperation Time after  " + signedJWT.getJWTClaimsSet().getExpirationTime());
		log.debug("Check date of token with current date {} ",
				new Date().before(signedJWT.getJWTClaimsSet().getExpirationTime()));//after
		validateTokenDate = new Date().before(signedJWT.getJWTClaimsSet().getExpirationTime());//after

	} catch (Exception e) {
		log.error(e);
		log.error(" Exception while validating token {} ", e.getMessage());
		isVerify = Boolean.FALSE;
		throw new InsightsCustomException("Exception while varifing token ==== " + e.getMessage());
	}

	if (!isVerify) {
		log.debug("Token signuture not match ");
		isVerify = Boolean.FALSE;
		throw new AuthorizationServiceException("Token signuture not match");
	} else if (!isTokenExistsInCache) {
		log.error("Token Not matched ");
		isVerify = Boolean.FALSE;
		throw new AuthenticationCredentialsNotFoundException("Token not found in cache");
	} else if (!validateTokenDate) {
		isVerify = Boolean.FALSE;
		throw new AccountExpiredException("Token Expire");
	} else {
		log.debug("Token verified sucessfully ==== ");
		isVerify = Boolean.TRUE;
	}

	log.debug(" is Token Verify  ====  {} ", isVerify);

	return isVerify;
}
 
Example #8
Source File: TektonClient.java    From secrets-proxy with Apache License 2.0 5 votes vote down vote up
/**
 * Invoke Tekton service Clients and call auth api.
 *
 * @param appName appName
 * @param user OneopsUser
 * @return <code>true</code> if user has admin access.
 */
@Override
public boolean authorizeUser(@Nonnull String appName, @Nonnull OneOpsUser user)
    throws IOException {

  log.info("Tekton Client services : authorization started");

  String org;
  String project;
  String env;
  /**
   * Get the <name> from AppGroup Split the appGroup "{org}_{project_name}_{env} "name with "_"
   * and get name for org, project and env
   */
  String[] nsArray = namespace.split(SecretsConstants.GROUP_SEP);
  if (nsArray.length == 3) {
    org = nsArray[0];
    project = nsArray[1];
    env = nsArray[2];
  } else {
    throw new AuthorizationServiceException("Provided appName is not authenticated");
  }

  Result<Void> result = tektonProxyClient.doAuth(user.getUsername(), org, project, env);
  if (result != null && result.isSuccessful()) {
    return true;
  }
  return false;
}
 
Example #9
Source File: SecretsService.java    From guardedbox with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * Finds a Secret Projection by secretId and checks if it exists and belongs to an ownerAccountId.
 *
 * @param <T> The projection type.
 * @param secretId The secretId.
 * @param ownerAccountId The accountId.
 * @param type The class of the projection.
 * @return The Secret Projection.
 */
protected <T extends SecretBaseProjection> T findAndCheckSecret(
        UUID secretId,
        UUID ownerAccountId,
        Class<T> type) {

    SecretBaseProjection secret = null;

    if (SecretValueProjection.class.equals(type)) {

        secret = secretsRepository.findValueBySecretId(secretId);

    } else if (SecretMustRotateKeyProjection.class.equals(type)) {

        secret = secretsRepository.findMustRotateKeyBySecretId(secretId);

    } else if (SecretBaseProjection.class.equals(type)) {

        secret = secretsRepository.findBaseBySecretId(secretId);

    } else {

        throw new IllegalArgumentException("Type must extend AccountBaseProjection");

    }

    if (secret == null) {
        throw new ServiceException(String.format("Secret %s does not exist", secretId))
                .setErrorCode("my-secrets.secret-does-not-exist");
    }

    if (ownerAccountId != null && !ownerAccountId.equals(secret.getOwnerAccount().getAccountId())) {
        throw new AuthorizationServiceException(String.format(
                "Secret %s cannot be managed by account %s since it belongs to account %s",
                secretId, ownerAccountId, secret.getOwnerAccount().getAccountId()));
    }

    return type.cast(secret);

}