Search in sources :

Example 56 with Token

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;
}
Also used : PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) ResourceOwner(org.forgerock.oauth2.core.ResourceOwner) ArrayList(java.util.ArrayList) AuthContext(com.sun.identity.authentication.AuthContext) PasswordCallback(javax.security.auth.callback.PasswordCallback) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) ResourceException(org.restlet.resource.ResourceException) IdRepoException(com.sun.identity.idm.IdRepoException) ResourceException(org.restlet.resource.ResourceException) ParseException(java.text.ParseException) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) SSOException(com.iplanet.sso.SSOException)

Example 57 with Token

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);
    }
}
Also used : SSOToken(com.iplanet.sso.SSOToken) ServiceConfigManager(com.sun.identity.sm.ServiceConfigManager) JSONException(org.json.JSONException) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) UnsupportedResponseTypeException(org.forgerock.oauth2.core.exceptions.UnsupportedResponseTypeException) SSOException(com.iplanet.sso.SSOException) InvalidClientException(org.forgerock.oauth2.core.exceptions.InvalidClientException) IdRepoException(com.sun.identity.idm.IdRepoException) SMSException(com.sun.identity.sm.SMSException) IOException(java.io.IOException) InvalidRequestException(org.forgerock.oauth2.core.exceptions.InvalidRequestException) InvalidScopeException(org.forgerock.oauth2.core.exceptions.InvalidScopeException)

Example 58 with Token

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");
    }
}
Also used : Locale(java.util.Locale) SSOToken(com.iplanet.sso.SSOToken) Set(java.util.Set) HashSet(java.util.HashSet) IdSearchResults(com.sun.identity.idm.IdSearchResults) JsonValue(org.forgerock.json.JsonValue) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) AMIdentity(com.sun.identity.idm.AMIdentity) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) AMIdentityRepository(com.sun.identity.idm.AMIdentityRepository) IdSearchControl(com.sun.identity.idm.IdSearchControl) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings) HashSet(java.util.HashSet)

Example 59 with Token

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();
    }
}
Also used : ServerException(org.forgerock.oauth2.core.exceptions.ServerException) JsonValue(org.forgerock.json.JsonValue) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) CoreTokenField(org.forgerock.openam.tokens.CoreTokenField) InvalidClientException(org.forgerock.oauth2.core.exceptions.InvalidClientException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) Delete(org.forgerock.json.resource.annotations.Delete)

Example 60 with Token

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);
}
Also used : ClientRegistration(org.forgerock.oauth2.core.ClientRegistration) HashMap(java.util.HashMap) JsonValue(org.forgerock.json.JsonValue) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings)

Aggregations

ServerException (org.forgerock.oauth2.core.exceptions.ServerException)33 JsonValue (org.forgerock.json.JsonValue)22 AccessToken (org.forgerock.oauth2.core.AccessToken)18 OAuth2Request (org.forgerock.oauth2.core.OAuth2Request)18 NotFoundException (org.forgerock.oauth2.core.exceptions.NotFoundException)18 CoreTokenException (org.forgerock.openam.cts.exceptions.CoreTokenException)18 SSOException (com.iplanet.sso.SSOException)16 OAuth2ProviderSettings (org.forgerock.oauth2.core.OAuth2ProviderSettings)16 UnauthorizedClientException (org.forgerock.oauth2.core.exceptions.UnauthorizedClientException)16 SSOToken (com.iplanet.sso.SSOToken)13 AMIdentity (com.sun.identity.idm.AMIdentity)12 IdRepoException (com.sun.identity.idm.IdRepoException)11 Set (java.util.Set)9 InvalidClientException (org.forgerock.oauth2.core.exceptions.InvalidClientException)9 HashMap (java.util.HashMap)8 HashSet (java.util.HashSet)8 InvalidGrantException (org.forgerock.oauth2.core.exceptions.InvalidGrantException)8 Test (org.testng.annotations.Test)8 Map (java.util.Map)6 AccessTokenVerifier (org.forgerock.oauth2.core.AccessTokenVerifier)6