use of org.forgerock.oauth2.core.Token in project OpenAM by OpenRock.
the class OpenAMResourceOwnerAuthenticator method authenticate.
private ResourceOwner authenticate(String username, char[] password, String realm, String service) {
ResourceOwner ret = null;
AuthContext lc = null;
try {
lc = new AuthContext(realm);
if (service != null) {
lc.login(AuthContext.IndexType.SERVICE, service, null, ServletUtils.getRequest(Request.getCurrent()), ServletUtils.getResponse(Response.getCurrent()));
} else {
lc.login(ServletUtils.getRequest(Request.getCurrent()), ServletUtils.getResponse(Response.getCurrent()));
}
while (lc.hasMoreRequirements()) {
Callback[] callbacks = lc.getRequirements();
ArrayList missing = new ArrayList();
// loop through the requires setting the needs..
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof NameCallback) {
NameCallback nc = (NameCallback) callbacks[i];
nc.setName(username);
} else if (callbacks[i] instanceof PasswordCallback) {
PasswordCallback pc = (PasswordCallback) callbacks[i];
pc.setPassword(password);
} else {
missing.add(callbacks[i]);
}
}
// there's missing requirements not filled by this
if (missing.size() > 0) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Missing requirements");
}
lc.submitRequirements(callbacks);
}
// validate the password..
if (lc.getStatus() == AuthContext.Status.SUCCESS) {
try {
// package up the token for transport..
ret = createResourceOwner(lc);
} catch (Exception e) {
logger.error("Unable to get SSOToken", e);
// because the system is likely down..
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
}
}
} catch (AuthLoginException le) {
logger.error("AuthException", le);
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, le);
} finally {
if (lc != null && AuthContext.Status.SUCCESS.equals(lc.getStatus())) {
try {
lc.logout();
logger.message("Logged user out.");
} catch (AuthLoginException e) {
logger.error("Exception caught logging out of AuthContext after successful login", e);
}
}
}
return ret;
}
use of org.forgerock.oauth2.core.Token in project OpenAM by OpenRock.
the class OpenAMOAuth2ProviderSettings method addServiceListener.
private void addServiceListener() {
try {
final SSOToken token = AccessController.doPrivileged(AdminTokenAction.getInstance());
final ServiceConfigManager serviceConfigManager = new ServiceConfigManager(token, OAuth2ProviderService.NAME, OAuth2ProviderService.VERSION);
if (serviceConfigManager.addListener(new OAuth2ProviderSettingsChangeListener()) == null) {
logger.error("Could not add listener to ServiceConfigManager instance. OAuth2 provider service " + "changes will not be dynamically updated for realm " + realm);
}
} catch (Exception e) {
String message = "OAuth2Utils::Unable to construct ServiceConfigManager: " + e;
logger.error(message, e);
throw OAuthProblemException.OAuthError.SERVER_ERROR.handle(null, message);
}
}
use of org.forgerock.oauth2.core.Token in project OpenAM by OpenRock.
the class IdentityManager method getResourceOwnerIdentity.
/**
* Gets a resource owner's identity.
*
* @param username The resource owner's username.
* @param realm The resource owner's realm.
* @return The resource owner's identity.
* @throws UnauthorizedClientException If the resource owner's identity cannot be found.
*/
public AMIdentity getResourceOwnerIdentity(String username, final String realm) throws UnauthorizedClientException {
final SSOToken token = AccessController.doPrivileged(AdminTokenAction.getInstance());
final AMIdentity amIdentity;
try {
final AMIdentityRepository amIdRepo = new AMIdentityRepository(token, realm);
final IdSearchControl idsc = new IdSearchControl();
idsc.setRecursive(true);
idsc.setAllReturnAttributes(true);
// search for the identity
final Set<AMIdentity> results = new HashSet<AMIdentity>();
idsc.setMaxResults(0);
IdSearchResults searchResults = amIdRepo.searchIdentities(IdType.USER, username, idsc);
if (searchResults != null && !searchResults.getResultAttributes().isEmpty()) {
results.addAll(searchResults.getSearchResults());
} else {
OAuth2ProviderSettings settings = providerSettingsFactory.get(new OAuth2Request() {
public <T> T getRequest() {
throw new UnsupportedOperationException("Realm parameter only OAuth2Request");
}
public <T> T getParameter(String name) {
if ("realm".equals(name)) {
return (T) realm;
}
throw new UnsupportedOperationException("Realm parameter only OAuth2Request");
}
public JsonValue getBody() {
throw new UnsupportedOperationException("Realm parameter only OAuth2Request");
}
@Override
public Locale getLocale() {
throw new UnsupportedOperationException();
}
});
final Map<String, Set<String>> avPairs = toAvPairMap(settings.getResourceOwnerAuthenticatedAttributes(), username);
idsc.setSearchModifiers(IdSearchOpModifier.OR, avPairs);
searchResults = amIdRepo.searchIdentities(IdType.USER, "*", idsc);
if (searchResults != null) {
results.addAll(searchResults.getSearchResults());
}
}
if (results.size() != 1) {
logger.error("No user profile or more than one profile found.");
throw new UnauthorizedClientException("Not able to get user from OpenAM");
}
amIdentity = results.iterator().next();
//if the client is deactivated return null
if (amIdentity.isActive()) {
return amIdentity;
} else {
return null;
}
} catch (Exception e) {
logger.error("Unable to get client AMIdentity: ", e);
throw new UnauthorizedClientException("Not able to get client from OpenAM");
}
}
use of org.forgerock.oauth2.core.Token in project OpenAM by OpenRock.
the class OAuth2UserApplications method deleteInstance.
/**
* Allows users to revoke an OAuth2 application. This will remove their consent and revoke any access and refresh
* tokens with a matching client id.
* @param context The request context.
* @param resourceId The id of the OAuth2 client.
* @return A promise of the removed application.
*/
@Delete
public Promise<ResourceResponse, ResourceException> deleteInstance(Context context, String resourceId) {
String userId = contextHelper.getUserId(context);
String realm = contextHelper.getRealm(context);
debug.message("Revoking access to OAuth2 client {} for user {}", resourceId, userId);
try {
oAuth2ProviderSettingsFactory.get(context).revokeConsent(userId, resourceId);
QueryFilter<CoreTokenField> queryFilter = and(getQueryFilter(userId, realm), equalTo(CLIENT_ID.getField(), resourceId));
JsonValue tokens = tokenStore.query(queryFilter);
if (tokens.asCollection().isEmpty()) {
return new org.forgerock.json.resource.NotFoundException().asPromise();
}
for (JsonValue token : tokens) {
String tokenId = getAttributeValue(token, ID.getOAuthField());
debug.message("Removing OAuth2 token {} with client {} for user {}", tokenId, resourceId, userId);
tokenStore.delete(tokenId);
}
return getResourceResponse(context, resourceId, tokens).asPromise();
} catch (CoreTokenException | InvalidClientException | NotFoundException | ServerException e) {
debug.message("Failed to revoke access to OAuth2 client {} for user {}", resourceId, userId, e);
return new InternalServerErrorException(e).asPromise();
} catch (InternalServerErrorException e) {
debug.message("Failed to revoke access to OAuth2 client {} for user {}", resourceId, userId, e);
return e.asPromise();
}
}
use of org.forgerock.oauth2.core.Token in project OpenAM by OpenRock.
the class OAuth2UserApplications method getResourceResponse.
private ResourceResponse getResourceResponse(Context context, String clientId, Iterable<JsonValue> tokens) throws NotFoundException, InvalidClientException, ServerException, InternalServerErrorException {
String realm = getAttributeValue(tokens.iterator().next(), REALM.getOAuthField());
OAuth2ProviderSettings oAuth2ProviderSettings = oAuth2ProviderSettingsFactory.get(context);
ClientRegistration clientRegistration = clientRegistrationStore.get(clientId, realm, context);
Map<String, String> scopeDescriptions = clientRegistration.getScopeDescriptions(getLocale(context));
Map<String, String> scopes = new HashMap<>();
for (JsonValue token : tokens) {
for (String scope : token.get(SCOPE.getOAuthField()).asSet(String.class)) {
if (scopeDescriptions.containsKey(scope)) {
scopes.put(scope, scopeDescriptions.get(scope));
} else {
scopes.put(scope, scope);
}
}
}
String displayName = clientRegistration.getDisplayName(getLocale(context));
String expiryDateTime = calculateExpiryDateTime(tokens, oAuth2ProviderSettings);
JsonValue content = json(object(field("_id", clientId), field("name", displayName), field("scopes", scopes), field("expiryDateTime", expiryDateTime)));
return Responses.newResourceResponse(clientId, String.valueOf(content.getObject().hashCode()), content);
}
Aggregations