Search in sources :

Example 1 with DeviceCode

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

the class OpenAMTokenStoreTest method shouldCreateDeviceCode.

@Test
public void shouldCreateDeviceCode() throws Exception {
    // Given
    OAuth2ProviderSettings providerSettings = mock(OAuth2ProviderSettings.class);
    given(providerSettingsFactory.get(any(OAuth2Request.class))).willReturn(providerSettings);
    given(providerSettings.getDeviceCodeLifetime()).willReturn(10);
    given(tokenStore.query(any(QueryFilter.class))).willReturn(json(array()));
    final RestletOAuth2Request oauth2Request = oAuth2RequestFactory.create(this.request);
    given(request.getAttributes()).willReturn(new ConcurrentHashMap<>(singletonMap("realm", (Object) "MY_REALM")));
    given(realmNormaliser.normalise("MY_REALM")).willReturn("MY_REALM");
    ResourceOwner resourceOwner = mock(ResourceOwner.class);
    given(resourceOwner.getId()).willReturn("RESOURCE_OWNER_ID");
    // When
    DeviceCode code = openAMtokenStore.createDeviceCode(asSet("one", "two"), resourceOwner, "CLIENT ID", "NONCE", "RESPONSE TYPE", "STATE", "ACR VALUES", "PROMPT", "UI LOCALES", "LOGIN HINT", 55, "CLAIMS", oauth2Request, "CODE CHALLENGE", "CODE METHOD");
    // Then
    assertThat(code.getScope()).containsOnly("one", "two");
    assertThat(code.getClientId()).isEqualTo("CLIENT ID");
    assertThat(code.getNonce()).isEqualTo("NONCE");
    assertThat(code.getResponseType()).isEqualTo("RESPONSE TYPE");
    assertThat(code.getState()).isEqualTo("STATE");
    assertThat(code.getAcrValues()).isEqualTo("ACR VALUES");
    assertThat(code.getPrompt()).isEqualTo("PROMPT");
    assertThat(code.getUiLocales()).isEqualTo("UI LOCALES");
    assertThat(code.getLoginHint()).isEqualTo("LOGIN HINT");
    assertThat(code.getClaims()).isEqualTo("CLAIMS");
    assertThat(code.getCodeChallenge()).isEqualTo("CODE CHALLENGE");
    assertThat(code.getCodeChallengeMethod()).isEqualTo("CODE METHOD");
    assertThat(code.getMaxAge()).isEqualTo(55);
    assertThat(code.getTokenName()).isEqualTo("device_code");
    assertThat(code.getExpiryTime()).isCloseTo(System.currentTimeMillis() + 10000, offset(1000L));
    assertThat(code.getTokenId()).matches("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}");
    assertThat(code.getUserCode()).matches("[" + OpenAMTokenStore.ALPHABET + "]{8}");
    assertThat(code.getRealm()).isEqualTo("MY_REALM");
}
Also used : RestletOAuth2Request(org.forgerock.oauth2.restlet.RestletOAuth2Request) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) QueryFilter(org.forgerock.util.query.QueryFilter) ResourceOwner(org.forgerock.oauth2.core.ResourceOwner) DeviceCode(org.forgerock.oauth2.core.DeviceCode) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings) RestletOAuth2Request(org.forgerock.oauth2.restlet.RestletOAuth2Request) Test(org.testng.annotations.Test)

Example 2 with DeviceCode

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

the class OpenAMTokenStoreTest method shouldReadValidDeviceCode.

@Test
public void shouldReadValidDeviceCode() throws Exception {
    // Given
    given(tokenStore.read("123")).willReturn(json(object(field("tokenName", asSet("device_code")), field("id", asSet("123")), field("user_code", asSet("456")), field("realm", asSet("/")), field("clientID", asSet("CLIENT_ID")))));
    final RestletOAuth2Request oauth2Request = oAuth2RequestFactory.create(this.request);
    given(request.getAttributes()).willReturn(new ConcurrentHashMap<>(singletonMap("realm", (Object) "/")));
    given(realmNormaliser.normalise("/")).willReturn("/");
    // When
    DeviceCode code = openAMtokenStore.readDeviceCode("CLIENT_ID", "123", oauth2Request);
    // Then
    assertThat(code.getTokenId()).isEqualTo("123");
    assertThat(code.getUserCode()).isEqualTo("456");
    assertThat(code.getClientId()).isEqualTo("CLIENT_ID");
}
Also used : DeviceCode(org.forgerock.oauth2.core.DeviceCode) RestletOAuth2Request(org.forgerock.oauth2.restlet.RestletOAuth2Request) Test(org.testng.annotations.Test)

Example 3 with DeviceCode

use of org.forgerock.oauth2.core.DeviceCode 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 4 with DeviceCode

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

the class OpenAMTokenStore method updateDeviceCode.

@Override
public void updateDeviceCode(DeviceCode code, OAuth2Request request) throws ServerException, NotFoundException, InvalidGrantException {
    try {
        readDeviceCode(code.getClientId(), code.getDeviceCode(), request);
        tokenStore.update(code);
    } catch (CoreTokenException e) {
        throw new ServerException("Could not update user code state");
    }
}
Also used : ServerException(org.forgerock.oauth2.core.exceptions.ServerException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException)

Example 5 with DeviceCode

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

the class OpenAMTokenStoreTest method shouldDeleteDeviceCode.

@Test
public void shouldDeleteDeviceCode() throws Exception {
    // Given
    DeviceCode code = new DeviceCode(json(object(field("tokenName", asSet("device_code")), field("id", asSet("123")), field("user_code", asSet("456")), field("realm", asSet("/")), field("clientID", asSet("CLIENT_ID")))));
    given(tokenStore.read("123")).willReturn(code);
    final RestletOAuth2Request oauth2Request = oAuth2RequestFactory.create(this.request);
    given(request.getAttributes()).willReturn(new ConcurrentHashMap<>(singletonMap("realm", (Object) "/")));
    given(realmNormaliser.normalise("/")).willReturn("/");
    // When
    openAMtokenStore.deleteDeviceCode("CLIENT_ID", "123", oauth2Request);
    // Then
    verify(tokenStore).delete("123");
}
Also used : DeviceCode(org.forgerock.oauth2.core.DeviceCode) RestletOAuth2Request(org.forgerock.oauth2.restlet.RestletOAuth2Request) Test(org.testng.annotations.Test)

Aggregations

DeviceCode (org.forgerock.oauth2.core.DeviceCode)8 RestletOAuth2Request (org.forgerock.oauth2.restlet.RestletOAuth2Request)4 Test (org.testng.annotations.Test)4 OAuth2ProviderSettings (org.forgerock.oauth2.core.OAuth2ProviderSettings)3 OAuth2Request (org.forgerock.oauth2.core.OAuth2Request)3 InvalidGrantException (org.forgerock.oauth2.core.exceptions.InvalidGrantException)3 ServerException (org.forgerock.oauth2.core.exceptions.ServerException)3 CoreTokenException (org.forgerock.openam.cts.exceptions.CoreTokenException)3 ResourceOwner (org.forgerock.oauth2.core.ResourceOwner)2 OAuth2Exception (org.forgerock.oauth2.core.exceptions.OAuth2Exception)2 Request (org.restlet.Request)2 Post (org.restlet.resource.Post)2 HashMap (java.util.HashMap)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 JsonValue (org.forgerock.json.JsonValue)1 DeviceCode (org.forgerock.oauth2.core.OAuth2Constants.DeviceCode)1 InvalidClientException (org.forgerock.oauth2.core.exceptions.InvalidClientException)1 RedirectUriMismatchException (org.forgerock.oauth2.core.exceptions.RedirectUriMismatchException)1 ResourceOwnerAuthenticationRequired (org.forgerock.oauth2.core.exceptions.ResourceOwnerAuthenticationRequired)1 ResourceOwnerConsentRequired (org.forgerock.oauth2.core.exceptions.ResourceOwnerConsentRequired)1