Search in sources :

Example 51 with Token

use of org.forgerock.oauth2.core.Token in project OpenAM by OpenRock.

the class AccessTokenProtectionFilter method beforeHandle.

@Override
protected int beforeHandle(Request request, Response response) {
    ChallengeResponse challengeResponse = request.getChallengeResponse();
    Status failure = null;
    if (challengeResponse == null) {
        failure = new Status(401, new InvalidTokenException());
    } else {
        String tokenId = challengeResponse.getRawValue();
        try {
            OAuth2Request oAuth2Request = requestFactory.create(request);
            AccessToken accessToken = tokenStore.readAccessToken(oAuth2Request, tokenId);
            if (accessToken == null || accessToken.isExpired()) {
                failure = new Status(401, new InvalidTokenException());
            } else if (requiredScope != null && !accessToken.getScope().contains(requiredScope)) {
                failure = new Status(403, new InsufficientScopeException(requiredScope));
            } else {
                oAuth2Request.setToken(AccessToken.class, accessToken);
            }
        } catch (ServerException e) {
            failure = new Status(500, e);
        } catch (NotFoundException e) {
            debug.message("Error loading token with id: " + tokenId, e);
            failure = new Status(404, e);
        } catch (InvalidGrantException e) {
            debug.message("Error loading token with id: " + tokenId, e);
            failure = new Status(401, new InvalidTokenException());
        }
    }
    if (failure != null) {
        response.setStatus(failure);
        return STOP;
    }
    return super.beforeHandle(request, response);
}
Also used : Status(org.restlet.data.Status) InvalidTokenException(org.forgerock.oauth2.core.exceptions.InvalidTokenException) InsufficientScopeException(org.forgerock.oauth2.core.exceptions.InsufficientScopeException) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) AccessToken(org.forgerock.oauth2.core.AccessToken) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) InvalidGrantException(org.forgerock.oauth2.core.exceptions.InvalidGrantException) ChallengeResponse(org.restlet.data.ChallengeResponse)

Example 52 with Token

use of org.forgerock.oauth2.core.Token in project OpenAM by OpenRock.

the class OpenAMResourceOwnerSessionValidator method validate.

/**
     * {@inheritDoc}
     */
public ResourceOwner validate(OAuth2Request request) throws ResourceOwnerAuthenticationRequired, AccessDeniedException, BadRequestException, InteractionRequiredException, LoginRequiredException, ServerException, NotFoundException {
    final OpenIdPrompt openIdPrompt = new OpenIdPrompt(request);
    if (!openIdPrompt.isValid()) {
        String message = "Invalid prompt parameter \"" + openIdPrompt.getOriginalValue() + "\"";
        logger.message(message);
        throw new BadRequestException(message);
    }
    SSOToken token = null;
    try {
        token = ssoTokenManager.createSSOToken(getHttpServletRequest(request.<Request>getRequest()));
    } catch (SSOException e) {
        logger.warning("Error authenticating user against OpenAM: ", e);
    }
    try {
        if (token == null) {
            token = ssoTokenManager.createSSOToken(request.getSession());
        }
    } catch (SSOException e) {
        logger.warning("Error authenticating user against OpenAM: ", e);
    }
    try {
        if (token != null) {
            try {
                // As the organization in the token is stored in lowercase, we need to lower case the auth2realm
                String auth2Realm = dnWrapper.orgNameToDN(realmNormaliser.normalise((String) request.getParameter("realm"))).toLowerCase();
                String tokenRealm = token.getProperty("Organization");
                // auth2Realm can't be null as we would have an error earlier
                if (!auth2Realm.equals(tokenRealm)) {
                    throw authenticationRequired(request);
                }
            } catch (SSOException e) {
                throw new AccessDeniedException(e);
            }
            if (openIdPrompt.containsLogin()) {
                throw authenticationRequired(request, token);
            }
            final String acrValuesStr = request.getParameter(ACR_VALUES);
            if (acrValuesStr != null) {
                setCurrentAcr(token, request, acrValuesStr);
            }
            try {
                final long authTime = stringToDate(token.getProperty(ISAuthConstants.AUTH_INSTANT)).getTime();
                if (isPastMaxAge(getMaxAge(request), authTime)) {
                    alterMaxAge(request);
                    throw authenticationRequired(request, token);
                }
                final AMIdentity id = IdUtils.getIdentity(AccessController.doPrivileged(AdminTokenAction.getInstance()), token.getProperty(Constants.UNIVERSAL_IDENTIFIER));
                return new OpenAMResourceOwner(id.getName(), id, authTime);
            } catch (Exception e) {
                //Exception as chance of MANY exception types here.
                logger.error("Error authenticating user against OpenAM: ", e);
                throw new LoginRequiredException();
            }
        } else if (PASSWORD.equals(request.getParameter(GRANT_TYPE))) {
            // been null from the attempted creation in L148.
            return getResourceOwner(request.getToken(AccessToken.class));
        } else {
            if (openIdPrompt.containsNone()) {
                logger.error("Not pre-authenticated and prompt parameter equals none.");
                if (request.getParameter(OAuth2Constants.Params.RESPONSE_TYPE) != null) {
                    throw new InteractionRequiredException(Utils.isOpenIdConnectFragmentErrorType(splitResponseType(request.<String>getParameter(RESPONSE_TYPE))) ? FRAGMENT : QUERY);
                } else {
                    throw new InteractionRequiredException();
                }
            } else if (!isRefreshToken(request)) {
                throw authenticationRequired(request);
            } else {
                return getResourceOwner(request.getToken(RefreshToken.class));
            }
        }
    } catch (SSOException | UnsupportedEncodingException | URISyntaxException e) {
        throw new AccessDeniedException(e);
    }
}
Also used : LoginRequiredException(org.forgerock.oauth2.core.exceptions.LoginRequiredException) InteractionRequiredException(org.forgerock.oauth2.core.exceptions.InteractionRequiredException) AccessDeniedException(org.forgerock.oauth2.core.exceptions.AccessDeniedException) SSOToken(com.iplanet.sso.SSOToken) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SSOException(com.iplanet.sso.SSOException) URISyntaxException(java.net.URISyntaxException) OpenIdPrompt(org.forgerock.openidconnect.OpenIdPrompt) URISyntaxException(java.net.URISyntaxException) InvalidClientAuthZHeaderException(org.forgerock.oauth2.core.exceptions.InvalidClientAuthZHeaderException) ParseException(java.text.ParseException) EncodingException(org.owasp.esapi.errors.EncodingException) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) SSOException(com.iplanet.sso.SSOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TemplateException(freemarker.template.TemplateException) InvalidClientException(org.forgerock.oauth2.core.exceptions.InvalidClientException) BadRequestException(org.forgerock.oauth2.core.exceptions.BadRequestException) LoginRequiredException(org.forgerock.oauth2.core.exceptions.LoginRequiredException) InteractionRequiredException(org.forgerock.oauth2.core.exceptions.InteractionRequiredException) IOException(java.io.IOException) InvalidRequestException(org.forgerock.oauth2.core.exceptions.InvalidRequestException) AccessDeniedException(org.forgerock.oauth2.core.exceptions.AccessDeniedException) RefreshToken(org.forgerock.oauth2.core.RefreshToken) AMIdentity(com.sun.identity.idm.AMIdentity) BadRequestException(org.forgerock.oauth2.core.exceptions.BadRequestException)

Example 53 with Token

use of org.forgerock.oauth2.core.Token in project OpenAM by OpenRock.

the class OpenAMClientDAO method delete.

/**
     * {@inheritDoc}
     */
public void delete(String clientId, OAuth2Request request) throws UnauthorizedClientException {
    try {
        //get the AMIdentity
        final SSOToken token = AccessController.doPrivileged(AdminTokenAction.getInstance());
        final String realm = request.getParameter(OAuth2Constants.Custom.REALM);
        AMIdentityRepository repo = idRepoFactory.create(realm, token);
        AMIdentity theID = null;
        IdSearchControl idsc = new IdSearchControl();
        idsc.setRecursive(true);
        idsc.setAllReturnAttributes(true);
        // search for the identity
        Set<AMIdentity> results;
        idsc.setMaxResults(0);
        IdSearchResults searchResults = repo.searchIdentities(IdType.AGENTONLY, clientId, idsc);
        results = searchResults.getSearchResults();
        if (results == null || results.size() != 1) {
            logger.error("OpenAMClientDAO.delete(): No client profile or more than one profile found.");
            throw new UnauthorizedClientException("Not able to get client from OpenAM");
        }
        theID = results.iterator().next();
        //if the client is deactivated return null
        if (!theID.isActive()) {
            theID = null;
        }
        //delete the AMIdentity
        Set<AMIdentity> identities = new HashSet<AMIdentity>();
        identities.add(theID);
        repo.deleteIdentities(identities);
    } catch (SSOException e) {
        logger.error("OpenAMClientDAO.delete(): Unable to delete client", e);
        throw new UnauthorizedClientException();
    } catch (IdRepoException e) {
        logger.error("OpenAMClientDAO.delete(): Unable to delete client", e);
        throw new UnauthorizedClientException();
    }
}
Also used : SSOToken(com.iplanet.sso.SSOToken) IdSearchResults(com.sun.identity.idm.IdSearchResults) 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) IdRepoException(com.sun.identity.idm.IdRepoException) SSOException(com.iplanet.sso.SSOException) HashSet(java.util.HashSet)

Example 54 with Token

use of org.forgerock.oauth2.core.Token in project OpenAM by OpenRock.

the class OpenAMClientDAO method create.

/**
     * {@inheritDoc}
     */
public void create(Client client, OAuth2Request request) throws InvalidClientMetadata {
    Map<String, Set<String>> attrs = createClientAttributeMap(client);
    try {
        final SSOToken token = AccessController.doPrivileged(AdminTokenAction.getInstance());
        final String realm = request.getParameter(OAuth2Constants.Custom.REALM);
        AMIdentityRepository repo = idRepoFactory.create(realm, token);
        repo.createIdentity(IdType.AGENTONLY, client.getClientID(), attrs);
    } catch (Exception e) {
        logger.error("ConnectClientRegistration.Validate(): Unable to create client", e);
        throw new InvalidClientMetadata();
    }
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) SSOToken(com.iplanet.sso.SSOToken) AMIdentityRepository(com.sun.identity.idm.AMIdentityRepository) InvalidClientMetadata(org.forgerock.openidconnect.exceptions.InvalidClientMetadata) IdRepoException(com.sun.identity.idm.IdRepoException) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) SSOException(com.iplanet.sso.SSOException)

Example 55 with Token

use of org.forgerock.oauth2.core.Token in project OpenAM by OpenRock.

the class OpenAMOAuth2ProviderSettingsFactory method addServiceListener.

private void addServiceListener() {
    try {
        final SSOToken token = AccessController.doPrivileged(AdminTokenAction.getInstance());
        final ServiceConfigManager serviceConfigManager = new ServiceConfigManager(token, OAuth2Constants.OAuth2ProviderService.NAME, OAuth2Constants.OAuth2ProviderService.VERSION);
        if (serviceConfigManager.addListener(this) == null) {
            logger.error("Could not add listener to ServiceConfigManager instance. OAuth2 provider service " + "removals will not be dynamically updated");
        }
    } 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) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException)

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