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

The following examples show how to use org.gluu.util.StringHelper#equals() . 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: UpdateOrganizationAction.java    From oxTrust with MIT License 6 votes vote down vote up
public String modify() {
	if (this.initialized) {
		return OxTrustConstants.RESULT_SUCCESS;
	}
	String resultOrganization = modifyOrganization();
	String resultApplliance = modifyApplliance();
	if (!StringHelper.equals(OxTrustConstants.RESULT_SUCCESS, resultOrganization)
			|| !StringHelper.equals(OxTrustConstants.RESULT_SUCCESS, resultApplliance)) {

		facesMessages.add(FacesMessage.SEVERITY_ERROR,
				facesMessages.evalResourceAsString("#{msg['organization.prepareUpdateFailed']}"));
		conversationService.endConversation();

		return OxTrustConstants.RESULT_FAILURE;
	}
	this.initialized = true;
	return OxTrustConstants.RESULT_SUCCESS;
}
 
Example 2
Source File: OpenIdClient.java    From oxTrust with MIT License 6 votes vote down vote up
@Override
public boolean isValidRequestState(final WebContext context) {
	final String state = context.getRequestParameter(AuthorizeRequestParam.STATE);
	logger.debug("oxAuth request state: '{}'", state);

	final Object sessionState = context.getSessionAttribute(getName() + SESSION_STATE_PARAMETER);
	logger.debug("Session context state: '{}'", sessionState);

	final boolean emptySessionState = StringHelper.isEmptyString(sessionState);
	if (emptySessionState) {
		return false;
	}

	final boolean result = StringHelper.equals(state, (String) sessionState);
	logger.debug("Is valid state: '{}'", result);

	return result;
}
 
Example 3
Source File: AppInitializer.java    From oxAuth with MIT License 6 votes vote down vote up
private void setDefaultAuthenticationMethod(GluuConfiguration configuration) {
	String currentAuthMethod = null;
	if (this.authenticationMode != null) {
		currentAuthMethod = this.authenticationMode.getName();
	}

	String actualAuthMethod = getActualDefaultAuthenticationMethod(configuration);

	if (!StringHelper.equals(currentAuthMethod, actualAuthMethod)) {
		authenticationMode = null;
		if (actualAuthMethod != null) {
			this.authenticationMode = new AuthenticationMode(actualAuthMethod);
		}

		authenticationModeInstance.destroy(authenticationModeInstance.get());
	}
}
 
Example 4
Source File: JsonConfigurationAction.java    From oxTrust with MIT License 5 votes vote down vote up
private void processPasswordProperty(AppConfiguration source, AppConfiguration current, String property)
		throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, EncryptionException {
	String currentValue = BeanUtils.getProperty(current, property);
	if (StringHelper.equals(currentValue, HIDDEN_PASSWORD_TEXT)) {
		BeanUtils.setProperty(current, property, BeanUtils.getSimpleProperty(source, property));
	} else {
		BeanUtils.setProperty(current, property, encryptionService.encrypt(currentValue));
	}
}
 
Example 5
Source File: OpenIdClient.java    From oxTrust with MIT License 5 votes vote down vote up
protected CommonProfile retrieveUserProfileFromUserInfoResponse(final WebContext context, final Jwt jwt, final UserInfoResponse userInfoResponse) {
	final CommonProfile profile = new CommonProfile();

	String nonceResponse = (String) jwt.getClaims().getClaim(JwtClaimName.NONCE);
       final String nonceSession = (String) context.getSessionAttribute(getName() + SESSION_NONCE_PARAMETER);
       logger.debug("Session nonce: '{}'", nonceSession);
       if (!StringHelper.equals(nonceSession, nonceResponse)) {
           logger.error("User info response:  nonce is not matching.");
           throw new CommunicationException("Nonce is not match" + nonceResponse + " : " + nonceSession);
       }

	String id = getFirstClaim(userInfoResponse, JwtClaimName.USER_NAME);
	if (StringHelper.isEmpty(id)) {
		id = getFirstClaim(userInfoResponse, JwtClaimName.SUBJECT_IDENTIFIER);
	}
	profile.setId(id);

	List<ClaimToAttributeMapping> claimMappings = this.appConfiguration.getOpenIdClaimMapping();
	if ((claimMappings == null) || (claimMappings.size() == 0)) {
		logger.info("Using default claims to attributes mapping");
		profile.setUserName(id);
		profile.setEmail(getFirstClaim(userInfoResponse, JwtClaimName.EMAIL));

		profile.setDisplayName(getFirstClaim(userInfoResponse, JwtClaimName.NAME));
		profile.setFirstName(getFirstClaim(userInfoResponse, JwtClaimName.GIVEN_NAME));
		profile.setFamilyName(getFirstClaim(userInfoResponse, JwtClaimName.FAMILY_NAME));
		profile.setZone(getFirstClaim(userInfoResponse, JwtClaimName.ZONEINFO));
		profile.setLocale(getFirstClaim(userInfoResponse, JwtClaimName.LOCALE));
	} else {
		for (ClaimToAttributeMapping mapping : claimMappings) {
			String attribute = mapping.getAttribute();
			String value = getFirstClaim(userInfoResponse, mapping.getClaim());
			profile.addAttribute(attribute, value);
			logger.trace("Adding attribute '{}' with value '{}'", attribute, value);
		}
	}

	return profile;
}
 
Example 6
Source File: RequestParameterService.java    From oxAuth with MIT License 5 votes vote down vote up
public Object getTypedValue(String stringValue, String type) {
    if (StringHelper.equals(Boolean.class.getName(), type)) {
        return Boolean.valueOf(stringValue);
    } else if (StringHelper.equals(Integer.class.getName(), type)) {
        return Integer.valueOf(stringValue);
    }

    return stringValue;
}
 
Example 7
Source File: AuthenticationService.java    From oxAuth with MIT License 5 votes vote down vote up
public AuthenticateRequest getAuthenticateRequest(AuthenticateRequestMessage requestMessage, AuthenticateResponse response) throws BadInputException {
    if (!StringHelper.equals(requestMessage.getRequestId(), response.getRequestId())) {
        throw new BadInputException("Wrong request for response data");
    }

    for (AuthenticateRequest request : requestMessage.getAuthenticateRequests()) {
        if (StringHelper.equals(request.getKeyHandle(), response.getKeyHandle())) {
            return request;
        }
    }

    throw new BadInputException("Responses keyHandle does not match any contained request");
}
 
Example 8
Source File: HttpService.java    From oxAuth with MIT License 5 votes vote down vote up
public boolean isContentTypeXml(HttpResponse httpResponse) {
	Header contentType = httpResponse.getEntity().getContentType();
	if (contentType == null) {
		return false;
	}

	String contentTypeValue = contentType.getValue();
	if (StringHelper.equals(contentTypeValue, ContentType.APPLICATION_XML.getMimeType()) || StringHelper.equals(contentTypeValue, ContentType.TEXT_XML.getMimeType())) {
		return true;
	}
	
	return false;
}
 
Example 9
Source File: CacheRefreshTimer.java    From oxTrust with MIT License 4 votes vote down vote up
private boolean isStartCacheRefresh(CacheRefreshConfiguration cacheRefreshConfiguration,
		GluuConfiguration currentConfiguration) {
	if (!currentConfiguration.isVdsCacheRefreshEnabled()) {
		return false;
	}

	long poolingInterval = StringHelper.toInteger(currentConfiguration.getVdsCacheRefreshPollingInterval()) * 60 * 1000;
	if (poolingInterval < 0) {
		return false;
	}

	String cacheRefreshServerIpAddress = currentConfiguration.getCacheRefreshServerIpAddress();
	// if (StringHelper.isEmpty(cacheRefreshServerIpAddress)) {
	// log.debug("There is no master Cache Refresh server");
	// return false;
	// }

	// Compare server IP address with cacheRefreshServerIp
	boolean cacheRefreshServer = false;
	try {
		Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
		for (NetworkInterface networkInterface : Collections.list(nets)) {
			Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
			for (InetAddress inetAddress : Collections.list(inetAddresses)) {
				if (StringHelper.equals(cacheRefreshServerIpAddress, inetAddress.getHostAddress())) {
					cacheRefreshServer = true;
					break;
				}
			}

			if (cacheRefreshServer) {
				break;
			}
		}
	} catch (SocketException ex) {
		log.error("Failed to enumerate server IP addresses", ex);
	}

	if (!cacheRefreshServer) {
		cacheRefreshServer = externalCacheRefreshService.executeExternalIsStartProcessMethods();
	}

	if (!cacheRefreshServer) {
		log.debug("This server isn't master Cache Refresh server");
		return false;
	}

	// Check if cache refresh specific configuration was loaded
	if (cacheRefreshConfiguration == null) {
		log.info("Failed to start cache refresh. Can't loading configuration from oxTrustCacheRefresh.properties");
		return false;
	}

	long timeDiffrence = System.currentTimeMillis() - this.lastFinishedTime;

	return timeDiffrence >= poolingInterval;
}
 
Example 10
Source File: Authenticator.java    From oxTrust with MIT License 4 votes vote down vote up
private String requestAccessToken(String oxAuthHost, String authorizationCode, String sessionState, String scopes,
		String clientID, String clientPassword) {
	OpenIdConfigurationResponse openIdConfiguration = openIdService.getOpenIdConfiguration();
	// 1. Request access token using the authorization code.
	TokenClient tokenClient1 = new TokenClient(openIdConfiguration.getTokenEndpoint());

	log.info("Sending request to token endpoint");
	String redirectURL = appConfiguration.getLoginRedirectUrl();
	log.info("redirectURI : " + redirectURL);
	TokenResponse tokenResponse = tokenClient1.execAuthorizationCode(authorizationCode, redirectURL, clientID,
			clientPassword);

	log.debug(" tokenResponse : " + tokenResponse);
	if (tokenResponse == null) {
		log.error("Get empty token response. User rcan't log into application");
		return OxTrustConstants.RESULT_NO_PERMISSIONS;
	}

	log.debug(" tokenResponse.getErrorType() : " + tokenResponse.getErrorType());

	String accessToken = tokenResponse.getAccessToken();
	log.debug(" accessToken : " + accessToken);

	String idToken = tokenResponse.getIdToken();
	log.debug(" idToken : " + idToken);

	if (idToken == null) {
		log.error("Failed to get id_token");
		return OxTrustConstants.RESULT_NO_PERMISSIONS;
	}

	log.info("Session validation successful. User is logged in");
	UserInfoClient userInfoClient = new UserInfoClient(openIdConfiguration.getUserInfoEndpoint());
	UserInfoResponse userInfoResponse = userInfoClient.execUserInfo(accessToken);
	if (userInfoResponse == null) {
		log.error("Get empty token response. User can't log into application");
		return OxTrustConstants.RESULT_NO_PERMISSIONS;
	}

	// Parse JWT
	Jwt jwt;
	try {
		jwt = Jwt.parse(idToken);
	} catch (InvalidJwtException ex) {
		log.error("Failed to parse id_token");
		return OxTrustConstants.RESULT_NO_PERMISSIONS;
	}

	// Check nonce
	String nonceResponse = (String) jwt.getClaims().getClaim(JwtClaimName.NONCE);
	String nonceSession = (String) identity.getSessionMap().get(OxTrustConstants.OXAUTH_NONCE);
	if (!StringHelper.equals(nonceSession, nonceResponse)) {
		log.error("User info response :  nonce is not matching.");
		return OxTrustConstants.RESULT_NO_PERMISSIONS;
	}

	// Determine uid
	List<String> uidValues = userInfoResponse.getClaims().get(JwtClaimName.USER_NAME);
	if ((uidValues == null) || (uidValues.size() == 0)) {
		log.error("User info response doesn't contains uid claim");
		return OxTrustConstants.RESULT_NO_PERMISSIONS;
	}
	// Check requested authentication method
	if (identity.getSessionMap().containsKey(OxTrustConstants.OXAUTH_ACR_VALUES)) {
		String requestAcrValues = (String) identity.getSessionMap().get(OxTrustConstants.OXAUTH_ACR_VALUES);
		String issuer = openIdConfiguration.getIssuer();
		String responseIssuer = (String) jwt.getClaims().getClaim(JwtClaimName.ISSUER);
		if (issuer == null || responseIssuer == null || !issuer.equals(responseIssuer)) {
			log.error("User info response :  Issuer.");
			return OxTrustConstants.RESULT_NO_PERMISSIONS;
		}

		List<String> acrValues = jwt.getClaims()
				.getClaimAsStringList(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE);
		if ((acrValues == null) || (acrValues.size() == 0) || !acrValues.contains(requestAcrValues)) {
			log.error("User info response doesn't contains acr claim");
			return OxTrustConstants.RESULT_NO_PERMISSIONS;
		}
		if (!acrValues.contains(requestAcrValues)) {
			log.error("User info response contains acr='{}' claim but expected acr='{}'", acrValues,
					requestAcrValues);
			return OxTrustConstants.RESULT_NO_PERMISSIONS;
		}
	}
	OauthData oauthData = identity.getOauthData();
	oauthData.setHost(oxAuthHost);
	oauthData.setUserUid(uidValues.get(0));
	oauthData.setAccessToken(accessToken);
	oauthData.setAccessTokenExpirationInSeconds(tokenResponse.getExpiresIn());
	oauthData.setScopes(scopes);
	oauthData.setIdToken(idToken);
	oauthData.setSessionState(sessionState);
	identity.setWorkingParameter(OxTrustConstants.OXAUTH_SSO_SESSION_STATE, Boolean.FALSE);
	log.info("user uid:" + oauthData.getUserUid());

	String result = authenticate();

	return result;
}
 
Example 11
Source File: AuthenticationFilter.java    From oxAuth with MIT License 4 votes vote down vote up
private void processBasicAuth(HttpServletRequest servletRequest, HttpServletResponse servletResponse, FilterChain filterChain) {
    boolean requireAuth = true;

    try {
        String header = servletRequest.getHeader("Authorization");
        if (tokenService.isBasicAuthToken(header)) {
            String base64Token = tokenService.getBasicToken(header);
            String token = new String(Base64.decodeBase64(base64Token), StandardCharsets.UTF_8);

            String username = "";
            String password = "";
            int delim = token.indexOf(":");

            if (delim != -1) {
                // oxAuth #677 URL decode the username and password
                username = URLDecoder.decode(token.substring(0, delim), Util.UTF8_STRING_ENCODING);
                password = URLDecoder.decode(token.substring(delim + 1), Util.UTF8_STRING_ENCODING);
            }

            requireAuth = !StringHelper.equals(username, identity.getCredentials().getUsername())
                    || !identity.isLoggedIn();

            // Only authenticate if username doesn't match Identity.username
            // and user isn't authenticated
            if (requireAuth) {
                if (!username.equals(identity.getCredentials().getUsername()) || !identity.isLoggedIn()) {
                    identity.getCredentials().setUsername(username);
                    identity.getCredentials().setPassword(password);

                    if (servletRequest.getRequestURI().endsWith("/token")
                            || servletRequest.getRequestURI().endsWith("/revoke")
                            || servletRequest.getRequestURI().endsWith("/revoke_session")
                            || servletRequest.getRequestURI().endsWith("/userinfo")
                            || servletRequest.getRequestURI().endsWith("/bc-authorize")) {
                        Client client = clientService.getClient(username);
                        if (client == null
                                || AuthenticationMethod.CLIENT_SECRET_BASIC != client.getAuthenticationMethod()) {
                            throw new Exception("The Token Authentication Method is not valid.");
                        }
                        requireAuth = !authenticator.authenticateClient(servletRequest);
                    } else {
                        requireAuth = !authenticator.authenticateUser(servletRequest);
                    }
                }
            }
        }

        if (!requireAuth) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
    } catch (Exception ex) {
        log.info("Basic authentication failed", ex);
    }

    if (requireAuth && !identity.isLoggedIn()) {
        sendError(servletResponse);
    }
}
 
Example 12
Source File: RegistrationService.java    From oxAuth with MIT License 4 votes vote down vote up
public DeviceRegistrationResult finishRegistration(RegisterRequestMessage requestMessage, RegisterResponse response, String userInum, Set<String> facets)
        throws BadInputException {
    RegisterRequest request = requestMessage.getRegisterRequest();
    String appId = request.getAppId();

    ClientData clientData = response.getClientData();
    clientDataValidationService.checkContent(clientData, RawRegistrationService.SUPPORTED_REGISTER_TYPES, request.getChallenge(), facets);

    RawRegisterResponse rawRegisterResponse = rawRegistrationService.parseRawRegisterResponse(response.getRegistrationData());
    rawRegistrationService.checkSignature(appId, clientData, rawRegisterResponse);

    Date now = new GregorianCalendar(TimeZone.getTimeZone("UTC")).getTime();
    DeviceRegistration deviceRegistration = rawRegistrationService.createDevice(userInum, rawRegisterResponse);
    deviceRegistration.setStatus(DeviceRegistrationStatus.ACTIVE);
    deviceRegistration.setApplication(appId);
    deviceRegistration.setCreationDate(now);

    int keyHandleHashCode = deviceRegistrationService.getKeyHandleHashCode(rawRegisterResponse.getKeyHandle());
    deviceRegistration.setKeyHandleHashCode(keyHandleHashCode);

    final String deviceRegistrationId = String.valueOf(System.currentTimeMillis());
    deviceRegistration.setId(deviceRegistrationId);

    String responseDeviceData = response.getDeviceData();
    if (StringHelper.isNotEmpty(responseDeviceData)) {
        try {
            String responseDeviceDataDecoded = new String(Base64Util.base64urldecode(responseDeviceData));
            DeviceData deviceData = ServerUtil.jsonMapperWithWrapRoot().readValue(responseDeviceDataDecoded, DeviceData.class);
            deviceRegistration.setDeviceData(deviceData);
        } catch (Exception ex) {
            throw new BadInputException(String.format("Device data is invalid: %s", responseDeviceData), ex);
        }
    }

    boolean approved = StringHelper.equals(RawRegistrationService.REGISTER_FINISH_TYPE, response.getClientData().getTyp());
    if (!approved) {
        log.debug("Registratio request with keyHandle '{}' was canceled", rawRegisterResponse.getKeyHandle());
        return new DeviceRegistrationResult(deviceRegistration, DeviceRegistrationResult.Status.CANCELED);
    }

    boolean twoStep = StringHelper.isNotEmpty(userInum);
    if (twoStep) {
        deviceRegistration.setDn(deviceRegistrationService.getDnForU2fDevice(userInum, deviceRegistrationId));

        // Check if there is device registration with keyHandle in LDAP already
        List<DeviceRegistration> foundDeviceRegistrations = deviceRegistrationService.findDeviceRegistrationsByKeyHandle(appId, deviceRegistration.getKeyHandle(), "oxId");
        if (foundDeviceRegistrations.size() != 0) {
            throw new BadInputException(String.format("KeyHandle %s was compromised", deviceRegistration.getKeyHandle()));
        }

		// Final registration entry should be without expiration
        deviceRegistration.clearExpiration();

		deviceRegistrationService.addUserDeviceRegistration(userInum, deviceRegistration);
    } else {
        deviceRegistration.setDn(deviceRegistrationService.getDnForOneStepU2fDevice(deviceRegistrationId));

        deviceRegistrationService.addOneStepDeviceRegistration(deviceRegistration);
    }

    return new DeviceRegistrationResult(deviceRegistration, DeviceRegistrationResult.Status.APPROVED);
}
 
Example 13
Source File: AuthenticationService.java    From oxAuth with MIT License 4 votes vote down vote up
public DeviceRegistrationResult finishAuthentication(AuthenticateRequestMessage requestMessage, AuthenticateResponse response, String userInum, Set<String> facets)
        throws BadInputException, DeviceCompromisedException {
    List<DeviceRegistration> deviceRegistrations = deviceRegistrationService.findUserDeviceRegistrations(userInum, requestMessage.getAppId());

    final AuthenticateRequest request = getAuthenticateRequest(requestMessage, response);

    DeviceRegistration usedDeviceRegistration = null;
    for (DeviceRegistration deviceRegistration : deviceRegistrations) {
        if (StringHelper.equals(request.getKeyHandle(), deviceRegistration.getKeyHandle())) {
            usedDeviceRegistration = deviceRegistration;
            break;
        }
    }

    if (usedDeviceRegistration == null) {
        throw new BadInputException("Failed to find DeviceRegistration for the given AuthenticateRequest");
    }

    if (usedDeviceRegistration.isCompromised()) {
        throw new DeviceCompromisedException(usedDeviceRegistration, "The device is marked as possibly compromised, and cannot be authenticated");
    }

    ClientData clientData = response.getClientData();
    clientDataValidationService.checkContent(clientData, RawAuthenticationService.SUPPORTED_AUTHENTICATE_TYPES, request.getChallenge(), facets);

    RawAuthenticateResponse rawAuthenticateResponse = rawAuthenticationService.parseRawAuthenticateResponse(response.getSignatureData());
    rawAuthenticationService.checkSignature(request.getAppId(), clientData, rawAuthenticateResponse,
            Base64Util.base64urldecode(usedDeviceRegistration.getDeviceRegistrationConfiguration().getPublicKey()));
    rawAuthenticateResponse.checkUserPresence();
    usedDeviceRegistration.checkAndUpdateCounter(rawAuthenticateResponse.getCounter());

    usedDeviceRegistration.setLastAccessTime(new Date());

    deviceRegistrationService.updateDeviceRegistration(userInum, usedDeviceRegistration);

    DeviceRegistrationResult.Status status = DeviceRegistrationResult.Status.APPROVED;

    boolean approved = StringHelper.equals(RawAuthenticationService.AUTHENTICATE_GET_TYPE, clientData.getTyp());
    if (!approved) {
        status = DeviceRegistrationResult.Status.CANCELED;
        log.debug("Authentication request with keyHandle '{}' was canceled", response.getKeyHandle());
    }

    return new DeviceRegistrationResult(usedDeviceRegistration, status);
}