org.gluu.persist.exception.EntryPersistenceException Java Examples

The following examples show how to use org.gluu.persist.exception.EntryPersistenceException. 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: MemberService.java    From oxTrust with MIT License 6 votes vote down vote up
private void removePersonFromGroups(GluuCustomPerson person) {
	log.debug("Removing person from associated group before deletion");
       String pesonDn = person.getDn();
	// Remove person from associated groups
	List<String> associatedGroupsDn = person.getMemberOf();
	for (String groupDn : associatedGroupsDn) {
	    if (!groupService.contains(groupDn)) {
	        continue;
	    }

	    GluuGroup group = groupService.getGroupByDn(groupDn);

		List<String> members = new ArrayList<String>(group.getMembers());
		members.remove(pesonDn);
		group.setMembers(members);
		try {
			groupService.updateGroup(group);
		} catch (EntryPersistenceException ex) {
		    log.error("Failed to remove preson '{}' from group '{}'", ex);
		}
	}
	log.debug("All group updated");
}
 
Example #2
Source File: GluuPersistenceService.java    From oxd with Apache License 2.0 6 votes vote down vote up
public Set<Rp> getRps() {
    try {
        List<RpObject> rpObjects = this.persistenceEntryManager.findEntries(String.format("%s,%s", new Object[]{getRpOu(), getOxdDn()}), RpObject.class, null);

        Set<Rp> result = new HashSet();
        for (RpObject ele : rpObjects) {
            Rp rp = MigrationService.parseRp(ele.getData());
            if (rp != null) {
                result.add(rp);
            } else {
                LOG.error("Failed to parse rp, id: {}, dn: {} ", ele.getId(), ele.getDn());
            }
        }
        return result;
    } catch (Exception e) {
        if (((e instanceof EntryPersistenceException)) && (e.getMessage().contains("Failed to find entries"))) {
            LOG.warn("Failed to fetch RpObjects. {} ", e.getMessage());
            return null;
        }
        LOG.error("Failed to fetch rps. Error: {} ", e.getMessage(), e);
    }
    return null;
}
 
Example #3
Source File: GluuPersistenceService.java    From oxd with Apache License 2.0 6 votes vote down vote up
public ExpiredObject getExpiredObject(String key) {
    try {
        ExpiredObject expiredObject = (ExpiredObject) this.persistenceEntryManager.find(getDnForExpiredObj(key), ExpiredObject.class, null);
        if (expiredObject != null) {
            expiredObject.setType(ExpiredObjectType.fromValue(expiredObject.getTypeString()));
            LOG.debug("Found ExpiredObject id: {} , ExpiredObject : {} ", key, expiredObject);
            return expiredObject;
        }

        LOG.error("Failed to fetch ExpiredObject by id: {} ", key);
        return null;
    } catch (Exception e) {
        if (((e instanceof EntryPersistenceException)) && (e.getMessage().contains("Failed to find entry"))) {
            LOG.warn("Failed to fetch ExpiredObject by id: {}. {} ", key, e.getMessage());
            return null;
        }
        LOG.error("Failed to fetch ExpiredObject by id: {} ", key, e);
    }
    return null;
}
 
Example #4
Source File: ExternalScriptContext.java    From oxAuth with MIT License 5 votes vote down vote up
protected CustomEntry getEntryByDn(String dn, String... ldapReturnAttributes) {
    try {
        return ldapEntryManager.find(dn, CustomEntry.class, ldapReturnAttributes);
    } catch (EntryPersistenceException epe) {
        log.error("Failed to find entry '{}'", dn);
    }

    return null;
}
 
Example #5
Source File: Fido2DeviceService.java    From oxTrust with MIT License 5 votes vote down vote up
public List<GluuFido2Device> findAllFido2Devices(GluuCustomPerson person) {
	try {
		String baseDnForU2fDevices = getDnForFido2Device(null, person.getInum());
		Filter inumFilter = Filter.createEqualityFilter(OxTrustConstants.PERSON_INUM, person.getInum());
		return ldapEntryManager.findEntries(baseDnForU2fDevices, GluuFido2Device.class, inumFilter);
	} catch (EntryPersistenceException e) {
		log.warn("No fido2 devices enrolled for " + person.getDisplayName());
		return new ArrayList<>();
	}
}
 
Example #6
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 #7
Source File: CleanerTimerTest.java    From oxAuth with MIT License 5 votes vote down vote up
@Test
public void u2fRequest_whichIsExpiredAndDeletable_MustBeRemoved() throws StringEncrypter.EncryptionException {
    final Client client = createClient();
    clientService.persist(client);

    // 1. create token
    String userInum = "";
    String appId = "https://testapp.com";
    final RequestMessageLdap request = u2fRegistrationService.storeRegisterRequestMessage(u2fRegistrationService.builRegisterRequestMessage(appId, userInum), userInum, userInum);

    // 2. request exists
    assertNotNull(u2fRegistrationService.getRegisterRequestMessage(request.getId()));

    // 3. clean up
    cleanerTimer.processImpl();
    cacheService.clear();

    // 4. request exists
    assertNotNull(u2fRegistrationService.getRegisterRequestMessage(request.getId()));

    final Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.MINUTE, -10);
    request.setExpirationDate(calendar.getTime());

    u2fRegistrationService.merge(request);

    // 5. clean up
    cleanerTimer.processImpl();
    cacheService.clear();

    // 6. no request in persistence
    try {
        u2fRegistrationService.getRegisterRequestMessage(request.getId());
        throw new AssertionError("No exception, expected EntryPersistenceException on find request.");
    } catch (EntryPersistenceException e) {
        // ignore
    }
}
 
Example #8
Source File: CleanUpClientTest.java    From oxAuth with MIT License 5 votes vote down vote up
@Test
@Parameters(value = "usedClients")
public void cleanUpClient(String usedClients) {
	Assert.assertNotNull(usedClients);
	List<String> usedClientsList = Arrays.asList(StringHelper.split(usedClients, ",", true, false));
	output("Used clients: " + usedClientsList);

	int clientsResultSetSize = 50;

	int countResults = 0;
	int countRemoved = 0;
	boolean existsMoreClients = true;
	while (existsMoreClients && countResults < 10000) {
		List<Client> clients = clientService.getAllClients(new String[] { "inum" }, clientsResultSetSize);

		existsMoreClients = clients.size() == clientsResultSetSize;
		countResults += clients.size();

		Assert.assertNotNull(clients);
		output("Found clients: " + clients.size());
		output("Total clients: " + countResults);

		for (Client client : clients) {
			String clientId = client.getClientId();
			if (!usedClientsList.contains(clientId)) {
				try {
					clientService.remove(client);
				} catch (EntryPersistenceException ex) {
					output("Failed to remove client: " + ex.getMessage());
				}
				countRemoved++;
			}
		}
	}

	output("Removed clients: " + countRemoved);
}
 
Example #9
Source File: AuthorizeRestWebServiceValidator.java    From oxAuth with MIT License 5 votes vote down vote up
public Client validateClient(String clientId, String state) {
    if (StringUtils.isBlank(clientId)) {
        throw new WebApplicationException(Response
                .status(Response.Status.BAD_REQUEST)
                .entity(errorResponseFactory.getErrorAsJson(AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT, state, "client_id is empty or blank."))
                .type(MediaType.APPLICATION_JSON_TYPE)
                .build());
    }

    try {
        final Client client = clientService.getClient(clientId);
        if (client == null) {
            throw new WebApplicationException(Response
                    .status(Response.Status.UNAUTHORIZED)
                    .entity(errorResponseFactory.getErrorAsJson(AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT, state, "Unable to find client."))
                    .type(MediaType.APPLICATION_JSON_TYPE)
                    .build());
        }
        if (client.isDisabled()) {
            throw new WebApplicationException(Response
                    .status(Response.Status.UNAUTHORIZED)
                    .entity(errorResponseFactory.getErrorAsJson(AuthorizeErrorResponseType.DISABLED_CLIENT, state, "Client is disabled."))
                    .type(MediaType.APPLICATION_JSON_TYPE)
                    .build());
        }

        return client;
    } catch (EntryPersistenceException e) { // Invalid clientId
        throw new WebApplicationException(Response
                .status(Response.Status.UNAUTHORIZED)
                .entity(errorResponseFactory.getErrorAsJson(AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT, state, "Unable to find client on AS."))
                .type(MediaType.APPLICATION_JSON_TYPE)
                .build());
    }
}
 
Example #10
Source File: UmaValidationService.java    From oxAuth with MIT License 5 votes vote down vote up
public void validatePermission(org.gluu.oxauth.model.uma.UmaPermission permission, Client client) {
    String resourceId = permission.getResourceId();
    if (StringHelper.isEmpty(resourceId)) {
        log.error("Resource id is empty");
        throw errorResponseFactory.createWebApplicationException(BAD_REQUEST, INVALID_RESOURCE_ID, "Resource id is empty");
    }

    try {
        UmaResource resource = resourceService.getResourceById(resourceId);
        if (resource == null) {
            log.error("Resource isn't registered or there are two resources with same Id");
            throw errorResponseFactory.createWebApplicationException(BAD_REQUEST, INVALID_RESOURCE_ID, "Resource is not registered.");
        }

        for (String s : permission.getScopes()) {
            if (resource.getScopes().contains(s)) {
                continue;
            }

            final Scope spontaneousScope = umaScopeService.getOrCreate(client, s, Sets.newHashSet(umaScopeService.getScopeIdsByDns(resource.getScopes())));
            if (spontaneousScope == null) {
                log.error("Scope isn't registered and is not allowed by spontaneous scopes. Scope: " + s);
                throw errorResponseFactory.createWebApplicationException(BAD_REQUEST, INVALID_SCOPE, "At least one of the scopes isn't registered");
            }
        }
        return;
    } catch (EntryPersistenceException ex) {
        log.error(ex.getMessage(), ex);
    }

    log.error("Resource isn't registered");
    throw errorResponseFactory.createWebApplicationException(BAD_REQUEST, INVALID_RESOURCE_ID, "Resource isn't registered");
}
 
Example #11
Source File: AuthenticationService.java    From oxAuth with MIT License 5 votes vote down vote up
private void updateLastLogonUserTime(User user) {
	if (!appConfiguration.getUpdateUserLastLogonTime()) {
		return;
	}

	CustomEntry customEntry = new CustomEntry();
	customEntry.setDn(user.getDn());

	List<String> personCustomObjectClassList = appConfiguration.getPersonCustomObjectClassList();
	if ((personCustomObjectClassList != null) && !personCustomObjectClassList.isEmpty()) {
		// Combine object classes from LDAP and configuration in one list
		Set<Object> customPersonCustomObjectClassList = new HashSet<Object>();
		customPersonCustomObjectClassList.add("gluuPerson");
		customPersonCustomObjectClassList.addAll(personCustomObjectClassList);
		if (user.getCustomObjectClasses() != null) { 
			customPersonCustomObjectClassList.addAll(Arrays.asList(user.getCustomObjectClasses()));
		}

		customEntry.setCustomObjectClasses(
				customPersonCustomObjectClassList.toArray(new String[customPersonCustomObjectClassList.size()]));
	} else {
		customEntry.setCustomObjectClasses(UserService.USER_OBJECT_CLASSES);
	}

	Date now = new GregorianCalendar(TimeZone.getTimeZone("UTC")).getTime();
	String nowDateString = ldapEntryManager.encodeTime(customEntry.getDn(), now);
	CustomAttribute customAttribute = new CustomAttribute("oxLastLogonTime", nowDateString);
	customEntry.getCustomAttributes().add(customAttribute);

	try {
		ldapEntryManager.merge(customEntry);
	} catch (EntryPersistenceException epe) {
		log.error("Failed to update oxLastLogonTime of user '{}'", user.getUserId());
	}
}
 
Example #12
Source File: ClientService.java    From oxAuth with MIT License 5 votes vote down vote up
public void updateAccessTime(Client client, boolean isUpdateLogonTime) {
	if (!appConfiguration.getUpdateClientAccessTime()) {
		return;
	}

	String clientDn = client.getDn();

	CustomEntry customEntry = new CustomEntry();
	customEntry.setDn(clientDn);
	customEntry.setCustomObjectClasses(CLIENT_OBJECT_CLASSES);

	Date now = new GregorianCalendar(TimeZone.getTimeZone("UTC")).getTime();
	String nowDateString = ldapEntryManager.encodeTime(customEntry.getDn(), now);

	CustomAttribute customAttributeLastAccessTime = new CustomAttribute("oxLastAccessTime", nowDateString);
	customEntry.getCustomAttributes().add(customAttributeLastAccessTime);

	if (isUpdateLogonTime) {
		CustomAttribute customAttributeLastLogonTime = new CustomAttribute("oxLastLogonTime", nowDateString);
		customEntry.getCustomAttributes().add(customAttributeLastLogonTime);
	}

	try {
		ldapEntryManager.merge(customEntry);
	} catch (EntryPersistenceException epe) {
		log.error("Failed to update oxLastAccessTime and oxLastLogonTime of client '{}'", clientDn);
	}

	removeFromCache(client);
}
 
Example #13
Source File: UserGroupService.java    From oxAuth with MIT License 5 votes vote down vote up
public boolean isUserInGroupOrMember(String groupDn, String personDn) {
	Filter ownerFilter = Filter.createEqualityFilter("owner", personDn);
	Filter memberFilter = Filter.createEqualityFilter("member", personDn);
	Filter searchFilter = Filter.createORFilter(ownerFilter, memberFilter);

	boolean isMemberOrOwner = false;
	try {
		isMemberOrOwner = ldapEntryManager.findEntries(groupDn, UserGroup.class, searchFilter, 1).size() > 0;

	} catch (EntryPersistenceException ex) {
		log.error("Failed to determine if person '{}' memeber or owner of group '{}'", personDn, groupDn, ex);
	}

	return isMemberOrOwner;
}
 
Example #14
Source File: SessionIdService.java    From oxAuth with MIT License 5 votes vote down vote up
private void mergeWithRetry(final SessionId sessionId) {
    final Pair<Date, Integer> expiration = expirationDate(sessionId.getCreationDate(), sessionId.getState());
    sessionId.setExpirationDate(expiration.getFirst());
    sessionId.setTtl(expiration.getSecond());

    EntryPersistenceException lastException = null;
    for (int i = 1; i <= MAX_MERGE_ATTEMPTS; i++) {
        try {
            persistenceEntryManager.merge(sessionId);
            externalEvent(new SessionEvent(SessionEventType.UPDATED, sessionId));
            return;
        } catch (EntryPersistenceException ex) {
            lastException = ex;
            if (ex.getCause() instanceof LDAPException) {
                LDAPException parentEx = ((LDAPException) ex.getCause());
                log.debug("LDAP exception resultCode: '{}'", parentEx.getResultCode().intValue());
                if ((parentEx.getResultCode().intValue() == ResultCode.NO_SUCH_ATTRIBUTE_INT_VALUE) ||
                        (parentEx.getResultCode().intValue() == ResultCode.ATTRIBUTE_OR_VALUE_EXISTS_INT_VALUE)) {
                    log.warn("Session entry update attempt '{}' was unsuccessfull", i);
                    continue;
                }
            }

            throw ex;
        }
    }

    log.error("Session entry update attempt was unsuccessfull after '{}' attempts", MAX_MERGE_ATTEMPTS);
    throw lastException;
}
 
Example #15
Source File: CleanUpTest.java    From oxTrust with MIT License 5 votes vote down vote up
/**
	 * Test search
	 * 
	 * @throws Exception
	 */
//	@Test
	@Parameters(value = "test.keep.persons")
	public void cleanUpGroups(String usedGroups) throws Exception {
		System.out.println("cleanup person Test initialted ");
		assertNotNull(usedGroups);
		List<String> usedGroupsList = Arrays.asList(StringHelper.split(usedGroups, ",", true, false));
		System.out.println("Used Groups: " + usedGroupsList);

		int groupsResultSetSize = 50;

		int countResults = 0;
		int countRemoved = 0;
		boolean existsMoreGroups = true;
		while (existsMoreGroups && countResults < 10000) {
			List<GluuGroup> groups = groupsService.getAllGroups();

			existsMoreGroups = groups.size() == groupsResultSetSize;
			countResults += groups.size();

			assertNotNull(groups);
			System.out.println("Found groups: " + groups.size());
			System.out.println("Total groups: " + countResults);

			for (GluuGroup group : groups) {
				// String clientId = person.getClientId();
				if (!usedGroupsList.contains(group.getInum())) {
					try {
						groupsService.removeGroup(group);
						countRemoved++;
					} catch (EntryPersistenceException ex) {
						System.out.println("Failed to remove group: " + ex.getMessage());
					}
				}
			}
		}

		System.out.println("Removed Persons: " + countRemoved);
	}
 
Example #16
Source File: CleanUpTest.java    From oxTrust with MIT License 5 votes vote down vote up
/**
	 * Test search
	 * 
	 * @throws Exception
	 */
//	@Test
	@Parameters(value = "test.keep.persons")
	public void cleanUpPersons(String usedPersons) throws Exception {
		System.out.println("cleanup person Test initialted ");
		assertNotNull(usedPersons);
		List<String> usedPersonsList = Arrays.asList(StringHelper.split(usedPersons, ",", true, false));
		System.out.println("Used persons: " + usedPersonsList);

		int personsResultSetSize = 50;

		int countResults = 0;
		int countRemoved = 0;
		boolean existsMorePersons = true;
		while (existsMorePersons && countResults < 10000) {
			List<GluuCustomPerson> persons = personService.findAllPersons(new String[] { "inum" });

			existsMorePersons = persons.size() == personsResultSetSize;
			countResults += persons.size();

			assertNotNull(persons);
			System.out.println("Found persons: " + persons.size());
			System.out.println("Total persons: " + countResults);

			for (GluuCustomPerson person : persons) {
				// String clientId = person.getClientId();
				if (!usedPersonsList.contains(person.getInum())) {
					try {
						memberService.removePerson(person);
						countRemoved++;
					} catch (EntryPersistenceException ex) {
						System.out.println("Failed to remove person: " + ex.getMessage());
					}
				}
			}
		}

		System.out.println("Removed Persons: " + countRemoved);
	}
 
Example #17
Source File: PersonImportAction.java    From oxTrust with MIT License 5 votes vote down vote up
public String importPersons() throws Exception {
	if (!fileDataToImport.isReady()) {
		facesMessages.add(FacesMessage.SEVERITY_ERROR, "File to import is invalid");
		return OxTrustConstants.RESULT_FAILURE;
	}
	log.debug("Attempting to add {} persons", fileDataToImport.getPersons().size());
	try {
		for (GluuCustomPerson person : fileDataToImport.getPersons()) {
			this.person = person;
			String result = initializePerson();
			if (result.equals(OxTrustConstants.RESULT_SUCCESS)) {
				result = save();
			}
			if (result.equals(OxTrustConstants.RESULT_SUCCESS)) {
				log.debug("Added new person: {}", person.getUid());
			} else {
				log.debug("Failed to add new person: {}", person.getUid());
				facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to add new person: '%s'", person.getUid());
			}
		}
	} catch (EntryPersistenceException ex) {
		log.error("Failed to add new person", ex);
		facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to import users");
		return OxTrustConstants.RESULT_FAILURE;
	}
	log.debug("All {} persons added successfully", fileDataToImport.getPersons().size());
	oxTrustAuditService.audit(fileDataToImport.getPersons().size() + " USERS IMPORTED ", identity.getUser(),
			(HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest());
	facesMessages.add(FacesMessage.SEVERITY_INFO, "Users successfully imported");
	removeFileToImport();
	return OxTrustConstants.RESULT_SUCCESS;
}
 
Example #18
Source File: PasswordResetAction.java    From oxTrust with MIT License 4 votes vote down vote up
public String start() throws ParseException {
	if (StringHelper.isEmpty(guid)) {
		sendExpirationError();
		return OxTrustConstants.RESULT_FAILURE;
	}
	setCode(guid);
	PasswordResetRequest passwordResetRequest;
	try {
		passwordResetRequest = passwordResetService.findPasswordResetRequest(getGuid());
	} catch (EntryPersistenceException ex) {
		log.error("Failed to find password reset request by '{}'", guid, ex);
		sendExpirationError();
		return OxTrustConstants.RESULT_FAILURE;
	}
	if (passwordResetRequest == null) {
		sendExpirationError();
		return OxTrustConstants.RESULT_FAILURE;
	}
	PasswordResetRequest personPasswordResetRequest = passwordResetService
			.findActualPasswordResetRequest(passwordResetRequest.getPersonInum());
	if (personPasswordResetRequest == null) {
		sendExpirationError();
		return OxTrustConstants.RESULT_FAILURE;
	}
	if (!StringHelper.equalsIgnoreCase(guid, personPasswordResetRequest.getOxGuid())) {
		sendExpirationError();
		return OxTrustConstants.RESULT_FAILURE;
	}
	this.request = personPasswordResetRequest;
	Calendar requestCalendarExpiry = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
	Calendar currentCalendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
	if (request != null) {
		requestCalendarExpiry.setTime(request.getCreationDate());
	}
	currentCalendar.add(Calendar.SECOND, -appConfiguration.getPasswordResetRequestExpirationTime());
	GluuCustomPerson person = personService.getPersonByInum(request.getPersonInum());
	GluuCustomAttribute question = null;
	if (person != null) {
		question = person.getGluuCustomAttribute("secretQuestion");
	}
	if ((request != null) && requestCalendarExpiry.after(currentCalendar)) {
		if (question != null) {
			securityQuestion = question.getValue();
		}
		return OxTrustConstants.RESULT_SUCCESS;
	} else {
		facesMessages.add(FacesMessage.SEVERITY_ERROR,
				"Your link is not valid or your user is not allowed to perform a password reset. If you want to initiate a reset password procedure please fill this form.");
		conversationService.endConversation();
		return OxTrustConstants.RESULT_FAILURE;
	}
}
 
Example #19
Source File: UserInfoRestWebServiceImpl.java    From oxAuth with MIT License 4 votes vote down vote up
private Response requestUserInfo(String accessToken, String authorization, HttpServletRequest request, SecurityContext securityContext) {

        if (tokenService.isBearerAuthToken(authorization)) {
            accessToken = tokenService.getBearerToken(authorization);
        }

        log.debug("Attempting to request User Info, Access token = {}, Is Secure = {}", accessToken, securityContext.isSecure());
        Response.ResponseBuilder builder = Response.ok();

        OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(request), Action.USER_INFO);

        try {
            if (!UserInfoParamsValidator.validateParams(accessToken)) {
                return response(400, UserInfoErrorResponseType.INVALID_REQUEST, "access token is not valid.");
            }

            AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(accessToken);

            if (authorizationGrant == null) {
                log.trace("Failed to find authorization grant by access_token: " + accessToken);
                return response(401, UserInfoErrorResponseType.INVALID_TOKEN);
            }
            oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, false);

            final AbstractToken accessTokenObject = authorizationGrant.getAccessToken(accessToken);
            if (accessTokenObject == null || !accessTokenObject.isValid()) {
                log.trace("Invalid access token object, access_token: {}, isNull: {}, isValid: {}", accessToken, accessTokenObject == null, false);
                return response(401, UserInfoErrorResponseType.INVALID_TOKEN);
            }

            if (authorizationGrant.getAuthorizationGrantType() == AuthorizationGrantType.CLIENT_CREDENTIALS) {
                return response(403, UserInfoErrorResponseType.INSUFFICIENT_SCOPE, "Grant object has client_credentials grant_type which is not valid.");
            }
            if (appConfiguration.getOpenidScopeBackwardCompatibility()
                    && !authorizationGrant.getScopes().contains(DefaultScope.OPEN_ID.toString())
                    && !authorizationGrant.getScopes().contains(DefaultScope.PROFILE.toString())) {
                return response(403, UserInfoErrorResponseType.INSUFFICIENT_SCOPE, "Both openid and profile scopes are not present.");
            }
            if (!appConfiguration.getOpenidScopeBackwardCompatibility() && !authorizationGrant.getScopes().contains(DefaultScope.OPEN_ID.toString())) {
                return response(403, UserInfoErrorResponseType.INSUFFICIENT_SCOPE, "Missed openid scope.");
            }

            oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, true);

            builder.cacheControl(ServerUtil.cacheControlWithNoStoreTransformAndPrivate());
            builder.header("Pragma", "no-cache");

            User currentUser = authorizationGrant.getUser();
            try {
                currentUser = userService.getUserByDn(authorizationGrant.getUserDn());
            } catch (EntryPersistenceException ex) {
                log.warn("Failed to reload user entry: '{}'", authorizationGrant.getUserDn());
            }

            if (authorizationGrant.getClient() != null
                    && authorizationGrant.getClient().getUserInfoEncryptedResponseAlg() != null
                    && authorizationGrant.getClient().getUserInfoEncryptedResponseEnc() != null) {
                KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.fromName(authorizationGrant.getClient().getUserInfoEncryptedResponseAlg());
                BlockEncryptionAlgorithm blockEncryptionAlgorithm = BlockEncryptionAlgorithm.fromName(authorizationGrant.getClient().getUserInfoEncryptedResponseEnc());
                builder.type("application/jwt");
                builder.entity(getJweResponse(
                        keyEncryptionAlgorithm,
                        blockEncryptionAlgorithm,
                        currentUser,
                        authorizationGrant,
                        authorizationGrant.getScopes()));
            } else if (authorizationGrant.getClient() != null
                    && authorizationGrant.getClient().getUserInfoSignedResponseAlg() != null) {
                SignatureAlgorithm algorithm = SignatureAlgorithm.fromString(authorizationGrant.getClient().getUserInfoSignedResponseAlg());
                builder.type("application/jwt");
                builder.entity(getJwtResponse(algorithm,
                        currentUser,
                        authorizationGrant,
                        authorizationGrant.getScopes()));
            } else {
                builder.type((MediaType.APPLICATION_JSON + ";charset=UTF-8"));
                builder.entity(getJSonResponse(currentUser,
                        authorizationGrant,
                        authorizationGrant.getScopes()));
            }
            return builder.build();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); // 500
        } finally {
            applicationAuditLogger.sendMessage(oAuth2AuditLog);
        }
    }
 
Example #20
Source File: CleanerTimerTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Test
public void u2fDevice_whichIsExpiredAndDeletable_MustBeRemoved() throws StringEncrypter.EncryptionException {
    final Client client = createClient();
    clientService.persist(client);

    // 1. create device
    String userInum = "";
    String appId = "https://testapp.com";
    final DeviceRegistration device = new DeviceRegistration();
    device.setStatus(DeviceRegistrationStatus.ACTIVE);
    device.setApplication(appId);
    device.setId(String.valueOf(System.currentTimeMillis()));
    device.setDn(deviceRegistrationService.getDnForU2fDevice(userInum, device.getId()));

    deviceRegistrationService.addOneStepDeviceRegistration(device);

    // 2. device exists
    assertNotNull(deviceRegistrationService.findUserDeviceRegistration(userInum, device.getId()));

    // 3. clean up
    cleanerTimer.processImpl();
    cacheService.clear();

    // 4. device exists
    assertNotNull(deviceRegistrationService.findUserDeviceRegistration(userInum, device.getId()));

    final Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.MINUTE, -10);
    device.setExpirationDate(calendar.getTime());

    deviceRegistrationService.merge(device);

    // 5. clean up
    cleanerTimer.processImpl();
    cacheService.clear();

    // 6. no device in persistence
    try {
        deviceRegistrationService.findUserDeviceRegistration(userInum, device.getId());
        throw new AssertionError("No exception, expected EntryPersistenceException on find.");
    } catch (EntryPersistenceException e) {
        // ignore
    }
}