Search in sources :

Example 11 with Token

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

the class RestletFormBodyAccessTokenVerifierTest method shouldCheckValid.

@Test
public void shouldCheckValid() throws Exception {
    // Given
    Form form = new Form();
    form.add("access_token", "freddy");
    Request request = new Request();
    request.setEntity(form.getWebRepresentation());
    OAuth2Request req = new RestletOAuth2Request(null, request);
    AccessToken token = new AccessToken(json(object()), "access_token", "freddy") {

        @Override
        public boolean isExpired() {
            return false;
        }
    };
    when(tokenStore.readAccessToken(req, "freddy")).thenReturn(token);
    // When
    AccessTokenVerifier.TokenState result = verifier.verify(req);
    // Then
    assertThat(result.isValid()).isTrue();
    assertThat(result.getTokenId()).isEqualTo("freddy");
    verify(tokenStore).readAccessToken(req, "freddy");
}
Also used : OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) Form(org.restlet.data.Form) AccessToken(org.forgerock.oauth2.core.AccessToken) Request(org.restlet.Request) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) AccessTokenVerifier(org.forgerock.oauth2.core.AccessTokenVerifier) Test(org.testng.annotations.Test)

Example 12 with Token

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

the class RestletFormBodyAccessTokenVerifierTest method shouldCheckExpired.

@Test
public void shouldCheckExpired() throws Exception {
    // Given
    Form form = new Form();
    form.add("access_token", "freddy");
    Request request = new Request();
    request.setEntity(form.getWebRepresentation());
    OAuth2Request req = new RestletOAuth2Request(null, request);
    AccessToken token = new AccessToken(json(object()), "access_token", "freddy") {

        @Override
        public boolean isExpired() {
            return true;
        }
    };
    when(tokenStore.readAccessToken(req, "freddy")).thenReturn(token);
    // When
    AccessTokenVerifier.TokenState result = verifier.verify(req);
    // Then
    assertThat(result.isValid()).isFalse();
    verify(tokenStore).readAccessToken(req, "freddy");
}
Also used : OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) Form(org.restlet.data.Form) AccessToken(org.forgerock.oauth2.core.AccessToken) Request(org.restlet.Request) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) AccessTokenVerifier(org.forgerock.oauth2.core.AccessTokenVerifier) Test(org.testng.annotations.Test)

Example 13 with Token

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

the class OpenAMTokenStore method createDeviceCode.

/**
     * {@inheritDoc}
     */
public DeviceCode createDeviceCode(Set<String> scope, ResourceOwner resourceOwner, String clientId, String nonce, String responseType, String state, String acrValues, String prompt, String uiLocales, String loginHint, Integer maxAge, String claims, OAuth2Request request, String codeChallenge, String codeChallengeMethod) throws ServerException, NotFoundException {
    logger.message("DefaultOAuthTokenStoreImpl::Creating Authorization code");
    final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
    final String deviceCode = UUID.randomUUID().toString();
    final StringBuilder codeBuilder = new StringBuilder(CODE_LENGTH);
    String userCode = null;
    int i;
    for (i = 0; i < NUM_RETRIES; i++) {
        for (int k = 0; k < CODE_LENGTH; k++) {
            codeBuilder.append(ALPHABET.charAt(secureRandom.nextInt(ALPHABET.length())));
        }
        try {
            readDeviceCode(codeBuilder.toString(), request);
            codeBuilder.delete(0, codeBuilder.length());
        // code can be found - try again
        } catch (InvalidGrantException e) {
            // Good, it doesn't exist yet.
            userCode = codeBuilder.toString();
            break;
        } catch (ServerException e) {
            logger.message("Could not query CTS, assume duplicate to be safe", e);
        }
    }
    if (i == NUM_RETRIES) {
        throw new ServerException("Could not generate a unique user code");
    }
    long expiryTime = System.currentTimeMillis() + (1000 * providerSettings.getDeviceCodeLifetime());
    String resourceOwnerId = resourceOwner == null ? null : resourceOwner.getId();
    final DeviceCode code = new DeviceCode(deviceCode, userCode, resourceOwnerId, clientId, nonce, responseType, state, acrValues, prompt, uiLocales, loginHint, maxAge, claims, expiryTime, scope, realmNormaliser.normalise(request.<String>getParameter(REALM)), codeChallenge, codeChallengeMethod);
    // Store in CTS
    try {
        tokenStore.create(code);
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "CREATED_DEVICE_CODE", code.toString() };
            auditLogger.logAccessMessage("CREATED_DEVICE_CODE", obs, null);
        }
    } catch (CoreTokenException e) {
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_CREATE_DEVICE_CODE", code.toString() };
            auditLogger.logErrorMessage("FAILED_CREATE_DEVICE_CODE", obs, null);
        }
        logger.error("Unable to create device code " + code, e);
        throw new ServerException("Could not create token in CTS");
    }
    request.setToken(DeviceCode.class, code);
    return code;
}
Also used : ServerException(org.forgerock.oauth2.core.exceptions.ServerException) DeviceCode(org.forgerock.oauth2.core.DeviceCode) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings) InvalidGrantException(org.forgerock.oauth2.core.exceptions.InvalidGrantException)

Example 14 with Token

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

the class OpenAMResourceOwnerAuthenticator method authenticate.

/**
     * {@inheritDoc}
     */
public ResourceOwner authenticate(OAuth2Request request, boolean useSession) throws NotFoundException {
    SSOToken token = null;
    try {
        SSOTokenManager mgr = SSOTokenManager.getInstance();
        token = mgr.createSSOToken(ServletUtils.getRequest(request.<Request>getRequest()));
    } catch (Exception e) {
        logger.warning("No SSO Token in request", e);
    }
    if (token == null || !useSession) {
        final String username = request.getParameter(USERNAME);
        final char[] password = request.getParameter(PASSWORD) == null ? null : request.<String>getParameter(PASSWORD).toCharArray();
        final String realm = realmNormaliser.normalise(request.<String>getParameter(OAuth2Constants.Custom.REALM));
        final String authChain = request.getParameter(AUTH_CHAIN);
        return authenticate(username, password, realm, authChain);
    } else {
        try {
            final AMIdentity id = IdUtils.getIdentity(AccessController.doPrivileged(AdminTokenAction.getInstance()), token.getProperty(Constants.UNIVERSAL_IDENTIFIER));
            long authTime = stringToDate(token.getProperty(ISAuthConstants.AUTH_INSTANT)).getTime();
            return new OpenAMResourceOwner(id.getName(), id, authTime);
        } catch (SSOException e) {
            logger.error("Unable to create ResourceOwner", e);
        } catch (ParseException e) {
            logger.error("Unable to create ResourceOwner", e);
        } catch (IdRepoException e) {
            logger.error("Unable to create ResourceOwner", e);
        }
    }
    return null;
}
Also used : SSOTokenManager(com.iplanet.sso.SSOTokenManager) SSOToken(com.iplanet.sso.SSOToken) AMIdentity(com.sun.identity.idm.AMIdentity) IdRepoException(com.sun.identity.idm.IdRepoException) SSOException(com.iplanet.sso.SSOException) ParseException(java.text.ParseException) 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 15 with Token

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

the class OpenAMScopeValidator method getUserInfo.

/**
     * {@inheritDoc}
     */
public UserInfoClaims getUserInfo(AccessToken token, OAuth2Request request) throws UnauthorizedClientException, NotFoundException {
    Map<String, Object> response = new HashMap<>();
    Bindings scriptVariables = new SimpleBindings();
    SSOToken ssoToken = getUsersSession(request);
    String realm;
    Set<String> scopes;
    AMIdentity id;
    OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
    Map<String, Set<String>> requestedClaimsValues = gatherRequestedClaims(providerSettings, request, token);
    try {
        if (token != null) {
            OpenIdConnectClientRegistration clientRegistration;
            try {
                clientRegistration = clientRegistrationStore.get(token.getClientId(), request);
            } catch (InvalidClientException e) {
                logger.message("Unable to retrieve client from store.");
                throw new NotFoundException("No valid client registration found.");
            }
            final String subId = clientRegistration.getSubValue(token.getResourceOwnerId(), providerSettings);
            //data comes from token when we have one
            realm = token.getRealm();
            scopes = token.getScope();
            id = identityManager.getResourceOwnerIdentity(token.getResourceOwnerId(), realm);
            response.put(OAuth2Constants.JWTTokenParams.SUB, subId);
            response.put(OAuth2Constants.JWTTokenParams.UPDATED_AT, getUpdatedAt(token.getResourceOwnerId(), token.getRealm(), request));
        } else {
            //otherwise we're simply reading claims into the id_token, so grab it from the request/ssoToken
            realm = DNMapper.orgNameToRealmName(ssoToken.getProperty(ISAuthConstants.ORGANIZATION));
            id = identityManager.getResourceOwnerIdentity(ssoToken.getProperty(ISAuthConstants.USER_ID), realm);
            String scopeStr = request.getParameter(OAuth2Constants.Params.SCOPE);
            scopes = splitScope(scopeStr);
        }
        scriptVariables.put(OAuth2Constants.ScriptParams.SCOPES, getScriptFriendlyScopes(scopes));
        scriptVariables.put(OAuth2Constants.ScriptParams.IDENTITY, id);
        scriptVariables.put(OAuth2Constants.ScriptParams.LOGGER, logger);
        scriptVariables.put(OAuth2Constants.ScriptParams.CLAIMS, response);
        scriptVariables.put(OAuth2Constants.ScriptParams.SESSION, ssoToken);
        scriptVariables.put(OAuth2Constants.ScriptParams.REQUESTED_CLAIMS, requestedClaimsValues);
        ScriptObject script = getOIDCClaimsExtensionScript(realm);
        try {
            return scriptEvaluator.evaluateScript(script, scriptVariables);
        } catch (ScriptException e) {
            logger.message("Error running OIDC claims script", e);
            throw new ServerException("Error running OIDC claims script: " + e.getMessage());
        }
    } catch (ServerException e) {
        //API does not allow ServerExceptions to be thrown!
        throw new NotFoundException(e.getMessage());
    } catch (SSOException e) {
        throw new NotFoundException(e.getMessage());
    }
}
Also used : ScriptObject(org.forgerock.openam.scripting.ScriptObject) OpenIdConnectClientRegistration(org.forgerock.openidconnect.OpenIdConnectClientRegistration) SSOToken(com.iplanet.sso.SSOToken) Set(java.util.Set) HashSet(java.util.HashSet) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) AMHashMap(com.iplanet.am.sdk.AMHashMap) HashMap(java.util.HashMap) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) SSOException(com.iplanet.sso.SSOException) SimpleBindings(javax.script.SimpleBindings) Bindings(javax.script.Bindings) ScriptException(javax.script.ScriptException) SimpleBindings(javax.script.SimpleBindings) AMIdentity(com.sun.identity.idm.AMIdentity) InvalidClientException(org.forgerock.oauth2.core.exceptions.InvalidClientException) JSONObject(org.json.JSONObject) ScriptObject(org.forgerock.openam.scripting.ScriptObject) 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