Java Code Examples for org.gluu.util.StringHelper#isNotEmpty()

The following examples show how to use org.gluu.util.StringHelper#isNotEmpty() . 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: AuthenticationService.java    From oxAuth with MIT License 6 votes vote down vote up
private boolean externalAuthenticate(String keyValue, String password) {
	for (int i = 0; i < this.ldapAuthConfigs.size(); i++) {
		GluuLdapConfiguration ldapAuthConfig = this.ldapAuthConfigs.get(i);
		PersistenceEntryManager ldapAuthEntryManager = this.ldapAuthEntryManagers.get(i);

		String primaryKey = "uid";
		if (StringHelper.isNotEmpty(ldapAuthConfig.getPrimaryKey())) {
			primaryKey = ldapAuthConfig.getPrimaryKey();
		}

		String localPrimaryKey = "uid";
		if (StringHelper.isNotEmpty(ldapAuthConfig.getLocalPrimaryKey())) {
			localPrimaryKey = ldapAuthConfig.getLocalPrimaryKey();
		}

		boolean authenticated = authenticate(ldapAuthConfig, ldapAuthEntryManager, keyValue, password, primaryKey,
				localPrimaryKey);
		if (authenticated) {
			return authenticated;
		}
	}

	return false;
}
 
Example 2
Source File: UpdateTrustRelationshipAction.java    From oxTrust with MIT License 6 votes vote down vote up
public String getSAML2URI(GluuAttribute attribute) {
	if (StringHelper.isNotEmpty(attribute.getSaml2Uri())) {
		return "SAML1 URI: " + attribute.getSaml2Uri();
	}
	List<String> attributeNames = new ArrayList<String>();
	attributeNames.add(attribute.getName());
	SchemaEntry schemaEntry = shemaService.getSchema();
	List<AttributeTypeDefinition> attributeTypes = shemaService.getAttributeTypeDefinitions(schemaEntry,
			attributeNames);
	String attributeName = attribute.getName();
	AttributeTypeDefinition attributeTypeDefinition = shemaService.getAttributeTypeDefinition(attributeTypes,
			attributeName);
	if (attributeTypeDefinition == null) {
		log.error("Failed to get OID for attribute name {}", attributeName);
		return null;
	}
	return "SAML2 URI: urn:oid:" + attributeTypeDefinition.getOID();
}
 
Example 3
Source File: RegistrationManagementAction.java    From oxTrust with MIT License 6 votes vote down vote up
public String search() {
	if (StringHelper.isNotEmpty(this.oldSearchPattern) && Util.equals(this.oldSearchPattern, this.searchPattern)) {
		return OxTrustConstants.RESULT_SUCCESS;
	}
	try {
	    if (StringHelper.isEmpty(this.searchPattern)) {
            this.attributes = attributeService.getAllAttributes();
	    } else {
	        this.attributes = attributeService.searchAttributes(this.searchPattern, OxTrustConstants.searchPersonsSizeLimit);
	    }
           for (GluuAttribute selectedAttribute : selectedAttributes) {
               if (!attributes.contains(selectedAttribute)) {
                   attributes.add(selectedAttribute);
               }
           }
		this.oldSearchPattern = this.searchPattern;
	} catch (Exception ex) {
		log.error("Failed to find attributes", ex);
		return OxTrustConstants.RESULT_FAILURE;
	}

	return OxTrustConstants.RESULT_SUCCESS;
}
 
Example 4
Source File: AppInitializer.java    From oxAuth with MIT License 5 votes vote down vote up
private Properties prepareAuthConnectionProperties(GluuLdapConfiguration persistenceAuthConfig, String persistenceType) {
	String prefix = persistenceType + ".";
	FileConfiguration configuration = configurationFactory.getPersistenceConfiguration().getConfiguration();

	Properties properties = (Properties) configuration.getProperties().clone();
	if (persistenceAuthConfig != null) {
		properties.setProperty(prefix + "servers", buildServersString(persistenceAuthConfig.getServers()));

		String bindDn = persistenceAuthConfig.getBindDN();
		if (StringHelper.isNotEmpty(bindDn)) {
			properties.setProperty(prefix + "bindDN", bindDn);
			properties.setProperty(prefix + "bindPassword", persistenceAuthConfig.getBindPassword());
		}
		properties.setProperty(prefix + "useSSL", Boolean.toString(persistenceAuthConfig.isUseSSL()));
		properties.setProperty(prefix + "maxconnections", Integer.toString(persistenceAuthConfig.getMaxConnections()));
		
		// Remove internal DB trustStoreFile property
		properties.remove(prefix + "ssl.trustStoreFile");			
		properties.remove(prefix + "ssl.trustStorePin");			
		properties.remove(prefix + "ssl.trustStoreFormat");			
	}

	EncryptionService securityService = encryptionServiceInstance.get();
	Properties decrypytedProperties = securityService.decryptAllProperties(properties);

	return decrypytedProperties;
}
 
Example 5
Source File: ImportPersonConfiguration.java    From oxTrust with MIT License 5 votes vote down vote up
private List<GluuAttribute> prepareAttributes() throws Exception {
	List<GluuAttribute> result = new ArrayList<GluuAttribute>();
	List<ImportPerson>  mappings = configurationFactory.getImportPersonConfig().getMappings();
	Iterator<ImportPerson> it = mappings.iterator();

	while (it.hasNext()) {
		ImportPerson importPerson = (ImportPerson) it.next();

			String attributeName = importPerson.getLdapName();
			boolean required = importPerson.getRequired();				

			if (StringHelper.isNotEmpty(attributeName)) {
				GluuAttribute attr = null;
				try {
					attr = attributeService.getAttributeByName(attributeName);
				} catch (EntryPersistenceException ex) {
					log.error("Failed to load attribute '{}' definition from LDAP", attributeName, ex);
				}
				if (attr == null) {
					log.warn("Failed to find attribute '{}' definition in LDAP", attributeName);
					attr = createAttributeFromConfig(importPerson);
					if (attr == null) {
						log.error("Failed to find attribute '{}' definition in '{}'", attributeName,
								GLUU_IMPORT_PERSON_PROPERTIES_FILE);
						continue;
					}
				} else {
					attr.setRequred(required);
				}
				result.add(attr);
			}
		//}
	}

	return result;
}
 
Example 6
Source File: ManagePersonAuthenticationAction.java    From oxTrust with MIT License 5 votes vote down vote up
public List<String> getPersonAuthenticationConfigurationNames() {
	if (this.customAuthenticationConfigNames == null) {
		this.customAuthenticationConfigNames = new ArrayList<String>();
		for (CustomScript customScript : this.customScripts) {
			if (customScript.isEnabled()) {
				String name = customScript.getName();
				if (StringHelper.isEmpty(name)) {
					continue;
				}
				this.customAuthenticationConfigNames.add(customScript.getName());
			}
		}
		boolean internalServerName = true;
		for (GluuLdapConfiguration ldapConfig : this.sourceConfigs) {
			if ((ldapConfig != null) && StringHelper.isNotEmpty(ldapConfig.getConfigId())
					&& ldapConfig.isEnabled()) {
				this.customAuthenticationConfigNames.add(ldapConfig.getConfigId());
				internalServerName = false;
			}
		}

		if (internalServerName) {
			this.customAuthenticationConfigNames.add(OxConstants.SCRIPT_TYPE_INTERNAL_RESERVED_NAME);
		}
		if (shouldEnableSimplePasswordAuth()
				&& !this.customAuthenticationConfigNames.contains(SIMPLE_PASSWORD_AUTH)) {
			this.customAuthenticationConfigNames.add(SIMPLE_PASSWORD_AUTH);
		}
	}
	return this.customAuthenticationConfigNames;
}
 
Example 7
Source File: SessionIdService.java    From oxAuth with MIT License 5 votes vote down vote up
public SessionId getSessionId() {
    String sessionId = cookieService.getSessionIdFromCookie();

    if (StringHelper.isNotEmpty(sessionId)) {
        return getSessionId(sessionId);
    } else {
    	log.trace("Session cookie not exists");
    }

    return null;
}
 
Example 8
Source File: UmaExpressionService.java    From oxAuth with MIT License 5 votes vote down vote up
public void evaluate(Map<UmaScriptByScope, UmaAuthorizationContext> scriptMap, List<UmaPermission> permissions) {
    for (UmaPermission permission : permissions) {
        UmaResource resource = resourceService.getResourceById(permission.getResourceId());
        if (StringHelper.isNotEmpty(resource.getScopeExpression())) {
            evaluateScopeExpression(scriptMap, permission, resource);
        } else {
            if (!evaluateByScopes(filterByScopeDns(scriptMap, permission.getScopeDns()))) {
                log.trace("Regular evaluation returns false, access FORBIDDEN.");
                throw errorResponseFactory.createWebApplicationException(Response.Status.FORBIDDEN, UmaErrorResponseType.FORBIDDEN_BY_POLICY, "Regular evaluation returns false, access FORBIDDEN.");
            }
        }
    }
}
 
Example 9
Source File: FileViewerAction.java    From oxTrust with MIT License 5 votes vote down vote up
public String getString(String fileName) {
	if (StringHelper.isNotEmpty(fileName)) {
		try {
			return FileUtils.readFileToString(new File(fileName),"UTF-8");
		} catch (IOException ex) {
			log.error("Failed to read file: '{}'", fileName, ex);
		}
	}
	return "invalid file name: " + fileName;
}
 
Example 10
Source File: ExternalAuthenticationService.java    From oxAuth with MIT License 5 votes vote down vote up
public CustomScriptConfiguration determineCustomScriptConfiguration(AuthenticationScriptUsageType usageType, int authStep, String acr) {
       CustomScriptConfiguration customScriptConfiguration;
       if (authStep == 1) {
           if (StringHelper.isNotEmpty(acr)) {
               customScriptConfiguration = getCustomScriptConfiguration(usageType, acr);
           } else {
          		customScriptConfiguration = getDefaultExternalAuthenticator(usageType);
           }
       } else {
           customScriptConfiguration = getCustomScriptConfiguration(usageType, acr);
       }

       return customScriptConfiguration;
}
 
Example 11
Source File: RegistrationService.java    From oxAuth with MIT License 5 votes vote down vote up
public RegisterRequestMessage builRegisterRequestMessage(String appId, String userInum) {
    if (applicationService.isValidateApplication()) {
        applicationService.checkIsValid(appId);
    }

    List<AuthenticateRequest> authenticateRequests = new ArrayList<AuthenticateRequest>();
    List<RegisterRequest> registerRequests = new ArrayList<RegisterRequest>();

    boolean twoStep = StringHelper.isNotEmpty(userInum);
    if (twoStep) {
        // In two steps we expects not empty userInum
        List<DeviceRegistration> deviceRegistrations = deviceRegistrationService.findUserDeviceRegistrations(userInum, appId);
        for (DeviceRegistration deviceRegistration : deviceRegistrations) {
            if (!deviceRegistration.isCompromised()) {
                try {
                    AuthenticateRequest authenticateRequest = u2fAuthenticationService.startAuthentication(appId, deviceRegistration);
                    authenticateRequests.add(authenticateRequest);
                } catch (DeviceCompromisedException ex) {
                    log.error("Faield to authenticate device", ex);
                }
            }
        }
    }

    RegisterRequest request = startRegistration(appId);
    registerRequests.add(request);

    return new RegisterRequestMessage(authenticateRequests, registerRequests);
}
 
Example 12
Source File: ExternalAuthenticationService.java    From oxAuth with MIT License 5 votes vote down vote up
public List<String> getAuthModesByAcrValues(List<String> acrValues) {
	List<String> authModes = new ArrayList<String>();

	for (String acrValue : acrValues) {
		if (StringHelper.isNotEmpty(acrValue)) {
			String customScriptName = StringHelper.toLowerCase(scriptName(acrValue));
			if (customScriptConfigurationsNameMap.containsKey(customScriptName)) {
				CustomScriptConfiguration customScriptConfiguration = customScriptConfigurationsNameMap.get(customScriptName);
				CustomScript customScript = customScriptConfiguration.getCustomScript();

				// Handle internal authentication method
				if (customScript.isInternal()) {
					authModes.add(scriptName(acrValue));
					continue;
				}

				CustomScriptType customScriptType = customScriptConfiguration.getCustomScript().getScriptType();
				BaseExternalType defaultImplementation = customScriptType.getDefaultImplementation();
				BaseExternalType pythonImplementation = customScriptConfiguration.getExternalType();
				if ((pythonImplementation != null) && (defaultImplementation != pythonImplementation)) {
					authModes.add(scriptName(acrValue));
				}
			}
		}
	}
	return authModes;
}
 
Example 13
Source File: Shibboleth3ConfService.java    From oxTrust with MIT License 5 votes vote down vote up
public HashMap<String, Object> initAttributeResolverParamMap() {
	List<NameIdConfig> nameIdConfigs = new ArrayList<NameIdConfig>();
	Set<GluuAttribute> nameIdAttributes = new HashSet<GluuAttribute>();

	AttributeResolverConfiguration attributeResolverConfiguration = configurationFactory.getAttributeResolverConfiguration();
	if ((attributeResolverConfiguration != null) && (attributeResolverConfiguration.getNameIdConfigs() != null)) {
		for (NameIdConfig nameIdConfig : attributeResolverConfiguration.getNameIdConfigs()) {
			if (StringHelper.isNotEmpty(nameIdConfig.getSourceAttribute()) && nameIdConfig.isEnabled()) {
				String attributeName = nameIdConfig.getSourceAttribute();
				GluuAttribute attribute = attributeService.getAttributeByName(attributeName);

				nameIdConfigs.add(nameIdConfig);
				nameIdAttributes.add(attribute);
			}
		}
	}

	HashMap<String, Object> attributeResolverParams = createAttributeMap(nameIdAttributes);
	attributeResolverParams.put("configs", nameIdConfigs);
	attributeResolverParams.put("attributes", nameIdAttributes);

	String baseUserDn = personService.getDnForPerson(null);
	String persistenceType = persistenceEntryManager.getPersistenceType(baseUserDn);

	log.debug(">>>>>>>>>> Shibboleth3ConfService.initAttributeResolverParamMap() - Persistance type: '{}'", persistenceType);
	attributeResolverParams.put("persistenceType", persistenceType);
	return attributeResolverParams;
}
 
Example 14
Source File: RecaptchaUtil.java    From oxTrust with MIT License 5 votes vote down vote up
public boolean verifyGoogleRecaptchaFromServletContext(String secretKey) {
	HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();
	String gRecaptchaResponse = httpServletRequest.getParameter("g-recaptcha-response");
	if (StringHelper.isNotEmpty(gRecaptchaResponse)) {
		return verifyGoogleRecaptcha(gRecaptchaResponse, secretKey);
	}

	return false;
}
 
Example 15
Source File: UmaScimClient.java    From SCIM-Client with Apache License 2.0 5 votes vote down vote up
/**
 * Recomputes a new RPT according to UMA workflow if the response passed as parameter has status code 401 (unauthorized).
 * @param response A Response object corresponding to the request obtained in the previous call to a service method
 * @return If the parameter passed has a status code different to 401, it returns false. Otherwise it returns the success
 * of the attempt made to get a new RPT
 */
@Override
boolean authorize(Response response) {

    boolean value = false;

    if (response.getStatus() == Response.Status.UNAUTHORIZED.getStatusCode()) {

        try {
            String permissionTicketResponse = response.getHeaderString("WWW-Authenticate");
            String permissionTicket = null;
            String asUri = null;

            String[] headerKeyValues = StringHelper.split(permissionTicketResponse, ",");
            for (String headerKeyValue : headerKeyValues) {
                if (headerKeyValue.startsWith("ticket=")) {
                    permissionTicket = headerKeyValue.substring(7);
                }
                if (headerKeyValue.startsWith("as_uri=")) {
                    asUri = headerKeyValue.substring(7);
                }
            }
            value= StringHelper.isNotEmpty(asUri) && StringHelper.isNotEmpty(permissionTicket)
                    && obtainAuthorizedRpt(asUri, permissionTicket);
        } catch (Exception e) {
            throw new ScimInitializationException(e.getMessage(), e);
        }
    }

    return value;
}
 
Example 16
Source File: FederationService.java    From oxTrust with MIT License 4 votes vote down vote up
public GluuSAMLFederationProposal getProposalByDn(String dn) {
	if (StringHelper.isNotEmpty(dn)) {
		return persistenceEntryManager.find(GluuSAMLFederationProposal.class, dn);
	}
	return null;
}
 
Example 17
Source File: AuthenticationService.java    From oxAuth with MIT License 4 votes vote down vote up
public boolean authenticate(String keyValue, String password, String primaryKey, String localPrimaryKey) {
	if (this.ldapAuthConfigs == null) {
		return authenticate(null, ldapEntryManager, keyValue, password, primaryKey, localPrimaryKey);
	}

	boolean authenticated = false;
	boolean protectionServiceEnabled = authenticationProtectionService.isEnabled();

	com.codahale.metrics.Timer.Context timerContext = metricService
			.getTimer(MetricType.OXAUTH_USER_AUTHENTICATION_RATE).time();
	try {
		for (int i = 0; i < this.ldapAuthConfigs.size(); i++) {
			GluuLdapConfiguration ldapAuthConfig = this.ldapAuthConfigs.get(i);
			PersistenceEntryManager ldapAuthEntryManager = this.ldapAuthEntryManagers.get(i);

			authenticated = authenticate(ldapAuthConfig, ldapAuthEntryManager, keyValue, password, primaryKey,
					localPrimaryKey);
			if (authenticated) {
				break;
			}
		}
	} finally {
		timerContext.stop();
	}
	String userId = null;
	if ((identity.getUser() != null) && StringHelper.isNotEmpty(identity.getUser().getUserId())) {
		userId = identity.getUser().getUserId();
	}
	setAuthenticatedUserSessionAttribute(userId, authenticated);

	MetricType metricType;
	if (authenticated) {
		metricType = MetricType.OXAUTH_USER_AUTHENTICATION_SUCCESS;
	} else {
		metricType = MetricType.OXAUTH_USER_AUTHENTICATION_FAILURES;
	}

	metricService.incCounter(metricType);

	if (protectionServiceEnabled) {
		authenticationProtectionService.storeAttempt(keyValue, authenticated);
		authenticationProtectionService.doDelayIfNeeded(keyValue);
	}

	return authenticated;
}
 
Example 18
Source File: AuthenticationFilter.java    From oxTrust with MIT License 4 votes vote down vote up
public String getOAuthRedirectUrl(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    String authorizeUrl = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_AUTHORIZE_URL, null);
    String clientScopes = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_CLIENT_SCOPE, null);

    String clientId = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_CLIENT_ID, null);
    String clientSecret = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_CLIENT_PASSWORD, null);
    if (clientSecret != null) {
        try {
            clientSecret = StringEncrypter.defaultInstance().decrypt(clientSecret, Configuration.instance().getCryptoPropertyValue());
        } catch (EncryptionException ex) {
            log.error("Failed to decrypt property: " + Configuration.OAUTH_PROPERTY_CLIENT_PASSWORD, ex);
        }
    }

    String redirectUri = constructRedirectUrl(request);

    List<String> scopes = Arrays.asList(clientScopes.split(StringUtils.SPACE));
    List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE);

    String nonce = UUID.randomUUID().toString();
    String rfp = UUID.randomUUID().toString();
    String jti = UUID.randomUUID().toString();

    // Lookup for relying party ID
    final String key = request.getParameter(ExternalAuthentication.CONVERSATION_KEY);
    request.getSession().setAttribute(SESSION_CONVERSATION_KEY, key);
    ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(key, request);

    String relyingPartyId = "";
    final RelyingPartyContext relyingPartyCtx = prc.getSubcontext(RelyingPartyContext.class);
    if (relyingPartyCtx != null) {
        relyingPartyId = relyingPartyCtx.getRelyingPartyId();
        log.info("relyingPartyId found: " + relyingPartyId);
    } else
        log.warn("No RelyingPartyContext was available");

    // JWT
    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider();
    JwtState jwtState = new JwtState(SignatureAlgorithm.HS256, clientSecret, cryptoProvider);
    jwtState.setRfp(rfp);
    jwtState.setJti(jti);
    if (relyingPartyId != null && !"".equals(relyingPartyId)) {
        String additionalClaims = String.format("{relyingPartyId: '%s'}", relyingPartyId);
        jwtState.setAdditionalClaims(new JSONObject(additionalClaims));
    } else
        log.warn("No relyingPartyId was available");
    String encodedState = jwtState.getEncodedJwt();

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
    authorizationRequest.setState(encodedState);

    Cookie currentShibstateCookie = getCurrentShibstateCookie(request);
    if (currentShibstateCookie != null) {
        String requestUri = decodeCookieValue(currentShibstateCookie.getValue());
        log.debug("requestUri = \"" + requestUri + "\"");

        String authenticationMode = determineAuthenticationMode(requestUri);

        if (StringHelper.isNotEmpty(authenticationMode)) {
            log.debug("acr_values = \"" + authenticationMode + "\"");
            authorizationRequest.setAcrValues(Arrays.asList(authenticationMode));
            updateShibstateCookie(response, currentShibstateCookie, requestUri, "/" + Configuration.OXAUTH_ACR_VALUES + "/" + authenticationMode);
        }
    }

    // Store for validation in session
    final HttpSession session = request.getSession(false);
    session.setAttribute(Configuration.SESSION_AUTH_STATE, encodedState);
    session.setAttribute(Configuration.SESSION_AUTH_NONCE, nonce);

    return authorizeUrl + "?" + authorizationRequest.getQueryString();
}
 
Example 19
Source File: ErrorHandlerService.java    From oxAuth with MIT License 4 votes vote down vote up
private void addMessage(Severity severity, String facesMessageId) {
    if (StringHelper.isNotEmpty(facesMessageId)) {
        facesMessages.add(FacesMessage.SEVERITY_ERROR, String.format("#{msg['%s']}", facesMessageId));
    }
}
 
Example 20
Source File: UpdateResourceAction.java    From oxTrust with MIT License 4 votes vote down vote up
public void removeResource(String resource) {
	if (StringHelper.isNotEmpty(resource)) {
		this.resources.remove(resource);
	}
}