com.webauthn4j.data.client.challenge.DefaultChallenge Java Examples

The following examples show how to use com.webauthn4j.data.client.challenge.DefaultChallenge. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ServerPropertyProviderImplTest.java    From webauthn4j-spring-security with Apache License 2.0 6 votes vote down vote up
@Test
public void provide_test() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setScheme("https");
    request.setServerName("origin.example.com");
    request.setServerPort(443);
    Challenge mockChallenge = new DefaultChallenge();
    when(challengeRepository.loadOrGenerateChallenge(request)).thenReturn(mockChallenge);
    when(optionsProvider.getEffectiveRpId(request)).thenReturn("rpid.example.com");

    ServerProperty serverProperty = target.provide(request);

    assertThat(serverProperty.getRpId()).isEqualTo("rpid.example.com");
    assertThat(serverProperty.getOrigin()).isEqualTo(new Origin("https://origin.example.com"));
    assertThat(serverProperty.getChallenge()).isEqualTo(mockChallenge);
}
 
Example #2
Source File: WebAuthnCredentialProviderTest.java    From keycloak-webauthn-authenticator with Apache License 2.0 6 votes vote down vote up
private WebAuthnCredentialModel getValidWebAuthnCredentialModel() {
    // mimic valid model created on Registration
    byte[] clientDataJSON = Base64.getUrlDecoder().decode("eyJjaGFsbGVuZ2UiOiJxOGJfc25BcFFCR0RTbEhLclVQWERBIiwib3JpZ2luIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwIiwidHlwZSI6IndlYmF1dGhuLmNyZWF0ZSJ9");
    byte[] attestationObject = Base64.getUrlDecoder().decode("o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YVjESZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2NBAAAAAAAAAAAAAAAAAAAAAAAAAAAAQNl5cq57gFloyTRaRzspkmVtaFjseFuas8LzmCa9_M40tZHwnOxuDFLj__IQkmCi9bwtXfxGU8L3IbXoJf-R1v6lAQIDJiABIVggHRj3_pRuFc4STvzzqO3WgO9cnj7u9R4OogbtOc4qA5kiWCAniOpK656_61Qnmx4hkWffohlH4JDbuytCpCtf9jrruA");

    Origin origin = new Origin("http://localhost:8080");
    Challenge challenge = new DefaultChallenge("q8b_snApQBGDSlHKrUPXDA");
    ServerProperty serverProperty = new ServerProperty(origin, "localhost", challenge, null);

    WebAuthnRegistrationContext registrationContext = new WebAuthnRegistrationContext(clientDataJSON, attestationObject, serverProperty, false);
    WebAuthnRegistrationContextValidator webAuthnRegistrationContextValidator = WebAuthnRegistrationContextValidator.createNonStrictRegistrationContextValidator();
    WebAuthnRegistrationContextValidationResponse response = webAuthnRegistrationContextValidator.validate(registrationContext);

    WebAuthnCredentialModel credential = new WebAuthnCredentialModel();
    credential.setAttestedCredentialData(response.getAttestationObject().getAuthenticatorData().getAttestedCredentialData());
    credential.setAttestationStatement(response.getAttestationObject().getAttestationStatement());
    credential.setCount(response.getAttestationObject().getAuthenticatorData().getSignCount());

    return credential;
}
 
Example #3
Source File: WebAuthnCredentialProviderTest.java    From keycloak-webauthn-authenticator with Apache License 2.0 6 votes vote down vote up
private WebAuthnAuthenticationContext getValidWebAuthnAuthenticationContext(String base64UrlCredentialId) {
    // mimic valid or invalid model created on Authentication
    byte[] credentialId = Base64Url.decode(base64UrlCredentialId);
    byte[] clientDataJSON = Base64Url.decode("eyJjaGFsbGVuZ2UiOiJ0R3o3R3RUQVE2T3FwVHpoOEtLQnFRIiwib3JpZ2luIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwIiwidHlwZSI6IndlYmF1dGhuLmdldCJ9");
    byte[] authenticatorData = Base64Url.decode("SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MBAAAAdg");
    byte[] signature = Base64Url.decode("MEUCIEaZhQ5dXi_C3IxU68ujLLt0DEcyk2EFPz_y45wYUA7AAiEAwkX86OFwpNzPRjSljTaTJVvZ_x9E6xnKhSmsKkUgmlo");
    Origin origin = new Origin("http://localhost:8080");
    Challenge challenge = new DefaultChallenge("tGz7GtTAQ6OqpTzh8KKBqQ");
    ServerProperty server = new ServerProperty(origin, "localhost", challenge, null);
    WebAuthnAuthenticationContext authenticationContext = new WebAuthnAuthenticationContext(
            credentialId,
            clientDataJSON,
            authenticatorData,
            signature,
            server,
            false
    );
    return authenticationContext;
}
 
Example #4
Source File: RegisterAuthenticator.java    From keycloak-webauthn-authenticator with Apache License 2.0 6 votes vote down vote up
@Override
public void requiredActionChallenge(RequiredActionContext context) {
    String userid = context.getUser().getId();
    String username = context.getUser().getUsername();
    Challenge challenge = new DefaultChallenge();
    String challengeValue = Base64Url.encode(challenge.getValue());
    String origin = context.getUriInfo().getBaseUri().getHost();
    context.getAuthenticationSession().setAuthNote(WebAuthnConstants.AUTH_CHALLENGE_NOTE, challengeValue);

    Response form = context.form()
            .setAttribute(WebAuthnConstants.ORIGIN, origin)
            .setAttribute(WebAuthnConstants.CHALLENGE, challengeValue)
            .setAttribute(WebAuthnConstants.USER_ID, userid)
            .setAttribute(WebAuthnConstants.USER_NAME, username)
            .createForm("webauthn-register.ftl");
    context.challenge(form);
}
 
Example #5
Source File: AssertionOptionsTest.java    From webauthn4j-spring-security with Apache License 2.0 6 votes vote down vote up
@Test
public void getter_test() {
    Challenge challenge = new DefaultChallenge();
    Long authenticationTimeout = 1000L;
    String rpId = "localhost";
    List<String> credentialIds = Collections.singletonList("credentialId");
    AuthenticationExtensionsClientInputs<AuthenticationExtensionClientInput<?>> authenticationExtensionsClientInputs = new AuthenticationExtensionsClientInputs<>();
    Parameters parameters = new Parameters(
            "username",
            "password",
            "credentialId",
            "clientDataJSON",
            "authenticatorData",
            "signature",
            "clientExtensionsJSON");
    AssertionOptions assertionOptions = new AssertionOptions(challenge, authenticationTimeout, rpId, credentialIds, authenticationExtensionsClientInputs, parameters);

    assertThat(assertionOptions.getChallenge()).isEqualTo(challenge);
    assertThat(assertionOptions.getAuthenticationTimeout()).isEqualTo(authenticationTimeout);
    assertThat(assertionOptions.getRpId()).isEqualTo(rpId);
    assertThat(assertionOptions.getCredentials()).isEqualTo(credentialIds);
    assertThat(assertionOptions.getAuthenticationExtensions()).isEqualTo(authenticationExtensionsClientInputs);
    assertThat(assertionOptions.getParameters()).isEqualTo(parameters);
}
 
Example #6
Source File: AssertionOptionsTest.java    From webauthn4j-spring-security with Apache License 2.0 6 votes vote down vote up
@Test
public void equals_hashCode_test() {
    Challenge challenge = new DefaultChallenge();
    Long authenticationTimeout = 1000L;
    String rpId = "localhost";
    List<String> credentialIds = Collections.singletonList("credentialId");
    AuthenticationExtensionsClientInputs<AuthenticationExtensionClientInput<?>> authenticationExtensionsClientInputs = new AuthenticationExtensionsClientInputs<>();
    Parameters parameters = new Parameters(
            "username",
            "password",
            "credentialId",
            "clientDataJSON",
            "authenticatorData",
            "signature",
            "clientExtensionsJSON");
    AssertionOptions instanceA = new AssertionOptions(challenge, authenticationTimeout, rpId, credentialIds, authenticationExtensionsClientInputs, parameters);
    AssertionOptions instanceB = new AssertionOptions(challenge, authenticationTimeout, rpId, credentialIds, authenticationExtensionsClientInputs, parameters);

    assertThat(instanceA).isEqualTo(instanceB);
    assertThat(instanceA).hasSameHashCodeAs(instanceB);
}
 
Example #7
Source File: PublicKeyCredentialCreationOptionsTest.java    From webauthn4j with Apache License 2.0 6 votes vote down vote up
@Test
void equals_hashCode_test() {
    String rpId = "example.com";
    Challenge challenge = new DefaultChallenge();

    PublicKeyCredentialParameters publicKeyCredentialParameters
            = new PublicKeyCredentialParameters(PublicKeyCredentialType.PUBLIC_KEY, COSEAlgorithmIdentifier.ES256);
    PublicKeyCredentialCreationOptions instanceA = new PublicKeyCredentialCreationOptions(
            new PublicKeyCredentialRpEntity(rpId, "example.com"),
            new PublicKeyCredentialUserEntity(),
            challenge,
            Collections.singletonList(publicKeyCredentialParameters)
    );
    PublicKeyCredentialCreationOptions instanceB = new PublicKeyCredentialCreationOptions(
            new PublicKeyCredentialRpEntity(rpId, "example.com"),
            new PublicKeyCredentialUserEntity(),
            challenge,
            Collections.singletonList(publicKeyCredentialParameters)
    );

    assertAll(
            () -> assertThat(instanceA).isEqualTo(instanceB),
            () -> assertThat(instanceA).hasSameHashCodeAs(instanceB)
    );
}
 
Example #8
Source File: WebAuthnAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public void authenticate(AuthenticationFlowContext context) {
    LoginFormsProvider form = context.form();
 
    Challenge challenge = new DefaultChallenge();
    String challengeValue = Base64Url.encode(challenge.getValue());
    context.getAuthenticationSession().setAuthNote(WebAuthnConstants.AUTH_CHALLENGE_NOTE, challengeValue);
    form.setAttribute(WebAuthnConstants.CHALLENGE, challengeValue);

    WebAuthnPolicy policy = getWebAuthnPolicy(context);
    String rpId = getRpID(context);
    form.setAttribute(WebAuthnConstants.RP_ID, rpId);

    UserModel user = context.getUser();
    boolean isUserIdentified = false;
    if (user != null) {
        // in 2 Factor Scenario where the user has already been identified
        WebAuthnAuthenticatorsBean authenticators = new WebAuthnAuthenticatorsBean(context.getSession(), context.getRealm(), user, getCredentialType());
        if (authenticators.getAuthenticators().isEmpty()) {
            // require the user to register webauthn authenticator
            return;
        }
        isUserIdentified = true;
        form.setAttribute(WebAuthnConstants.ALLOWED_AUTHENTICATORS, authenticators);
    } else {
        // in ID-less & Password-less Scenario
        // NOP
    }
    form.setAttribute(WebAuthnConstants.IS_USER_IDENTIFIED, Boolean.toString(isUserIdentified));

    // read options from policy
    String userVerificationRequirement = policy.getUserVerificationRequirement();
    form.setAttribute(WebAuthnConstants.USER_VERIFICATION, userVerificationRequirement);

    context.challenge(form.createLoginWebAuthn());
}
 
Example #9
Source File: WebAuthnAuthenticationRequestTest.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@Test
public void getter_test() {
    Challenge challenge = new DefaultChallenge();
    byte[] clientDataJSON = TestDataUtil.createClientDataJSON(ClientDataType.GET);
    byte[] authenticatorData = new AuthenticatorDataConverter(objectConverter).convert(TestDataUtil.createAuthenticatorData());
    ServerProperty serverProperty = new ServerProperty(
            new Origin("https://example.com"),
            "example.com",
            challenge,
            new byte[]{0x43, 0x21}
    );
    WebAuthnAuthenticationRequest request = new WebAuthnAuthenticationRequest(
            new byte[]{0x01, 0x23},
            clientDataJSON,
            authenticatorData,
            new byte[]{0x45, 0x56},
            "",
            serverProperty,
            true,
            true,
            Collections.singletonList("uvi")
    );
    assertThat(request.getCredentialId()).isEqualTo(new byte[]{0x01, 0x23});
    assertThat(request.getClientDataJSON()).isEqualTo(clientDataJSON);
    assertThat(request.getAuthenticatorData()).isEqualTo(authenticatorData);
    assertThat(request.getSignature()).isEqualTo(new byte[]{0x45, 0x56});
    assertThat(request.getClientExtensionsJSON()).isEqualTo("");
    assertThat(request.getServerProperty()).isEqualTo(serverProperty);
    assertThat(request.isUserVerificationRequired()).isEqualTo(true);
    assertThat(request.isUserPresenceRequired()).isEqualTo(true);
    assertThat(request.getExpectedAuthenticationExtensionIds()).isEqualTo(Collections.singletonList("uvi"));
}
 
Example #10
Source File: ChallengeDeserializer.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Challenge deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    String str = p.getValueAsString();
    try {
        return new DefaultChallenge(str);
    } catch (IllegalArgumentException e) {
        throw new InvalidFormatException(null, "value is out of range", str, DefaultChallenge.class);
    }
}
 
Example #11
Source File: TestDataUtil.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
public static Challenge createChallenge() {
    UUID uuid = UUID.randomUUID();
    long hi = uuid.getMostSignificantBits();
    long lo = uuid.getLeastSignificantBits();
    byte[] challengeValue = ByteBuffer.allocate(16).putLong(hi).putLong(lo).array();
    return new DefaultChallenge(challengeValue);
}
 
Example #12
Source File: BeanAssertUtilTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void validate_clientData_with_tokenBinding_null_test() {
    CollectedClientData collectedClientData = new CollectedClientData(
            ClientDataType.GET,
            new DefaultChallenge(),
            new Origin("https://example.com"),
            null
    );

    BeanAssertUtil.validate(collectedClientData);
}
 
Example #13
Source File: WebAuthn4jAuthenticator.java    From keycloak-webauthn-authenticator with Apache License 2.0 5 votes vote down vote up
private Map<String, String> generateParameters(RealmModel realm, URI baseUri) {
    Map<String, String> params = new HashMap<>();
    Challenge challenge = new DefaultChallenge();
    params.put(WebAuthnConstants.CHALLENGE, Base64Url.encode(challenge.getValue()));
    params.put(WebAuthnConstants.RPID, baseUri.getHost());
    params.put(WebAuthnConstants.ORIGIN, UriUtils.getOrigin(baseUri));
    return params;
}
 
Example #14
Source File: OptionsProviderImplTest.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@Test
public void getAttestationOptions_test() {
    Challenge challenge = new DefaultChallenge();
    byte[] credentialId = new byte[]{0x01, 0x23, 0x45};
    WebAuthnUserDetailsService userDetailsService = mock(WebAuthnUserDetailsService.class);
    WebAuthnUserDetails userDetails = mock(WebAuthnUserDetails.class);
    Authenticator authenticator = mock(Authenticator.class, RETURNS_DEEP_STUBS);
    List<Authenticator> authenticators = Collections.singletonList(authenticator);
    ChallengeRepository challengeRepository = mock(ChallengeRepository.class);

    MockHttpServletRequest mockRequest = new MockHttpServletRequest();

    when(userDetailsService.loadUserByUsername(any())).thenReturn(userDetails);
    doReturn(new byte[0]).when(userDetails).getUserHandle();
    doReturn(authenticators).when(userDetails).getAuthenticators();
    when(authenticator.getAttestedCredentialData().getCredentialId()).thenReturn(credentialId);
    when(challengeRepository.loadOrGenerateChallenge(mockRequest)).thenReturn(challenge);

    OptionsProvider optionsProvider = new OptionsProviderImpl(userDetailsService, challengeRepository);
    optionsProvider.setRpId("example.com");
    optionsProvider.setRpName("rpName");
    optionsProvider.setRpIcon("data://dummy");

    AttestationOptions attestationOptions = optionsProvider.getAttestationOptions(mockRequest, "dummy", null);
    assertThat(attestationOptions.getRelyingParty().getId()).isEqualTo("example.com");
    assertThat(attestationOptions.getRelyingParty().getName()).isEqualTo("rpName");
    assertThat(attestationOptions.getRelyingParty().getIcon()).isEqualTo("data://dummy");
    assertThat(attestationOptions.getChallenge()).isEqualTo(challenge);
    assertThat(attestationOptions.getCredentials()).containsExactly(Base64UrlUtil.encodeToString(credentialId));

}
 
Example #15
Source File: AttestationOptionsTest.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@Test
public void equals_hashCode_test() {
    PublicKeyCredentialRpEntity rpEntity = new PublicKeyCredentialRpEntity("rpId", "rpName", "rpIcon");
    WebAuthnPublicKeyCredentialUserEntity userEntity = new WebAuthnPublicKeyCredentialUserEntity(Base64UrlUtil.encodeToString("userHandle".getBytes()), "username");
    Challenge challenge = new DefaultChallenge();
    List<PublicKeyCredentialParameters> pubKeyCredParams = Collections.singletonList(new PublicKeyCredentialParameters(PublicKeyCredentialType.PUBLIC_KEY, COSEAlgorithmIdentifier.ES256));
    Long registrationTimeout = 1000L;
    List<String> credentialIds = Collections.singletonList("credentialId");
    AuthenticationExtensionsClientInputs<RegistrationExtensionClientInput<?>> authenticationExtensionsClientInputs = new AuthenticationExtensionsClientInputs<>();
    AttestationOptions instanceA = new AttestationOptions(rpEntity, userEntity, challenge, pubKeyCredParams, registrationTimeout, credentialIds, authenticationExtensionsClientInputs);
    AttestationOptions instanceB = new AttestationOptions(rpEntity, userEntity, challenge, pubKeyCredParams, registrationTimeout, credentialIds, authenticationExtensionsClientInputs);

    assertThat(instanceA).isEqualTo(instanceB);
    assertThat(instanceA).hasSameHashCodeAs(instanceB);
}
 
Example #16
Source File: WebAuthnAuthenticationRequestTest.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@Test
public void equals_hashCode_test() {
    Challenge challenge = new DefaultChallenge();
    byte[] clientDataJSON = TestDataUtil.createClientDataJSON(ClientDataType.GET);
    byte[] authenticatorData = new AuthenticatorDataConverter(objectConverter).convert(TestDataUtil.createAuthenticatorData());
    WebAuthnAuthenticationRequest requestA = new WebAuthnAuthenticationRequest(
            new byte[]{0x01, 0x23},
            clientDataJSON,
            authenticatorData,
            new byte[]{0x45, 0x56},
            "",
            new ServerProperty(
                    new Origin("https://example.com"),
                    "example.com",
                    challenge,
                    new byte[]{0x43, 0x21}
            ),
            true,
            Collections.singletonList("uvi")
    );
    WebAuthnAuthenticationRequest requestB = new WebAuthnAuthenticationRequest(
            new byte[]{0x01, 0x23},
            clientDataJSON,
            authenticatorData,
            new byte[]{0x45, 0x56},
            "",
            new ServerProperty(
                    new Origin("https://example.com"),
                    "example.com",
                    challenge,
                    new byte[]{0x43, 0x21}
            ),
            true,
            Collections.singletonList("uvi")
    );

    assertThat(requestA).isEqualTo(requestB);
    assertThat(requestA).hasSameHashCodeAs(requestB);
}
 
Example #17
Source File: ServerPropertyTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void equals_hashCode_test() {
    Challenge challenge = new DefaultChallenge();
    ServerProperty serverPropertyA = TestDataUtil.createServerProperty(challenge);
    ServerProperty serverPropertyB = TestDataUtil.createServerProperty(challenge);

    assertAll(
            () -> assertThat(serverPropertyA).isEqualTo(serverPropertyB),
            () -> assertThat(serverPropertyA).hasSameHashCodeAs(serverPropertyB)
    );
}
 
Example #18
Source File: FIDOU2FAuthenticatorRegistrationValidationTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void validate_with_bad_attestationStatement_test() {
    String rpId = "example.com";
    Challenge challenge = new DefaultChallenge();
    PublicKeyCredentialParameters publicKeyCredentialParameters
            = new PublicKeyCredentialParameters(PublicKeyCredentialType.PUBLIC_KEY, COSEAlgorithmIdentifier.ES256);
    PublicKeyCredentialCreationOptions credentialCreationOptions = new PublicKeyCredentialCreationOptions(
            new PublicKeyCredentialRpEntity(rpId, "example.com"),
            new PublicKeyCredentialUserEntity(),
            challenge,
            Collections.singletonList(publicKeyCredentialParameters)
    );

    AuthenticatorAttestationResponse authenticatorAttestationResponse = clientPlatform.create(credentialCreationOptions).getAuthenticatorResponse();
    Set<String> transports = authenticatorTransportConverter.convertSetToStringSet(authenticatorAttestationResponse.getTransports());
    ServerProperty serverProperty = new ServerProperty(origin, rpId, challenge, null);
    RegistrationRequest registrationRequest
            = new RegistrationRequest(
            authenticatorAttestationResponse.getAttestationObject(),
            authenticatorAttestationResponse.getClientDataJSON(),
            transports
    );
    RegistrationParameters registrationParameters
            = new RegistrationParameters(
            serverProperty,
            false,
            true,
            Collections.emptyList()
    );
    WebAuthnManager target = new WebAuthnManager(
            Collections.singletonList(fidoU2FAttestationStatementValidator),
            new TrustAnchorCertPathTrustworthinessValidator(mock(TrustAnchorsResolver.class)),
            new DefaultSelfAttestationTrustworthinessValidator()
    );

    assertThrows(BadAttestationStatementException.class,
            () -> target.validate(registrationRequest, registrationParameters)
    );
}
 
Example #19
Source File: BeanAssertUtilTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void validate_clientData_with_origin_null_test() {
    CollectedClientData collectedClientData = new CollectedClientData(
            ClientDataType.GET,
            new DefaultChallenge(),
            null,
            new TokenBinding(TokenBindingStatus.PRESENT, new byte[32])
    );

    assertThrows(ConstraintViolationException.class,
            () -> BeanAssertUtil.validate(collectedClientData)
    );
}
 
Example #20
Source File: BeanAssertUtilTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void validate_clientData_with_clientDataType_null_test() {
    CollectedClientData collectedClientData = new CollectedClientData(
            null,
            new DefaultChallenge(),
            new Origin("https://example.com"),
            new TokenBinding(TokenBindingStatus.PRESENT, new byte[32])
    );

    assertThrows(ConstraintViolationException.class,
            () -> BeanAssertUtil.validate(collectedClientData)
    );
}
 
Example #21
Source File: BeanAssertUtilTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void validate_clientData_test() {
    CollectedClientData collectedClientData = new CollectedClientData(
            ClientDataType.GET,
            new DefaultChallenge(),
            new Origin("https://example.com"),
            new TokenBinding(TokenBindingStatus.PRESENT, new byte[32])
    );

    BeanAssertUtil.validate(collectedClientData);
}
 
Example #22
Source File: ChallengeValidatorTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void verifyChallenge_test_without_saved_challenge() {

    Challenge challengeA = new DefaultChallenge(new byte[]{0x00});
    Challenge challengeB = null;

    CollectedClientData collectedClientData = new CollectedClientData(ClientDataType.CREATE, challengeA, null, null);
    ServerProperty serverProperty = new ServerProperty(null, null, challengeB, null);

    //When
    assertThrows(MissingChallengeException.class,
            () -> target.validate(collectedClientData, serverProperty)
    );
}
 
Example #23
Source File: ChallengeValidatorTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void verifyChallenge_test_with_different_challenge() {

    Challenge challengeA = new DefaultChallenge(new byte[]{0x00});
    Challenge challengeB = new DefaultChallenge(new byte[]{0x01});

    CollectedClientData collectedClientData = new CollectedClientData(ClientDataType.CREATE, challengeA, null, null);
    ServerProperty serverProperty = new ServerProperty(null, null, challengeB, null);

    //When
    assertThrows(BadChallengeException.class,
            () -> target.validate(collectedClientData, serverProperty)
    );
}
 
Example #24
Source File: ChallengeValidatorTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void verifyChallenge_test1() {

    Challenge challengeA = new DefaultChallenge(new byte[]{0x00});
    Challenge challengeB = new DefaultChallenge(new byte[]{0x00});

    CollectedClientData collectedClientData = new CollectedClientData(ClientDataType.CREATE, challengeA, null, null);
    ServerProperty serverProperty = new ServerProperty(null, null, challengeB, null);

    //When
    target.validate(collectedClientData, serverProperty);
}
 
Example #25
Source File: CollectedClientDataConverterTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void convert_clientDataBase64UrlString_with_new_keys_test() {
    //noinspection SpellCheckingInspection
    String clientDataJson = "{\"challenge\":\"Tgup0LZZQKinvtQcZFYdRw\",\"new_keys_may_be_added_here\":\"do not compare clientDataJSON against a template. See https://goo.gl/yabPex\",\"origin\":\"http://localhost:8080\",\"tokenBinding\":{\"status\":\"not-supported\"},\"type\":\"webauthn.create\"}";
    String clientDataBase64UrlString = Base64UrlUtil.encodeToString(clientDataJson.getBytes(StandardCharsets.UTF_8));
    CollectedClientData collectedClientData = target.convert(clientDataBase64UrlString);
    assertAll(
            () -> assertThat(collectedClientData.getType()).isEqualTo(ClientDataType.CREATE),
            () -> assertThat(collectedClientData.getChallenge()).isEqualTo(new DefaultChallenge("Tgup0LZZQKinvtQcZFYdRw")),
            () -> assertThat(collectedClientData.getOrigin()).isEqualTo(new Origin("http://localhost:8080"))
    );
}
 
Example #26
Source File: CollectedClientDataConverterTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void convert_deserialization_test() {
    //noinspection SpellCheckingInspection
    String clientDataJson = "{\"challenge\":\"tk31UH1ETGGTPj33OhOMzw\",\"origin\":\"http://localhost:8080\",\"tokenBinding\":{\"status\":\"not-supported\"},\"type\":\"webauthn.get\"}";
    String clientDataBase64UrlString = Base64UrlUtil.encodeToString(clientDataJson.getBytes(StandardCharsets.UTF_8));
    CollectedClientData collectedClientData = target.convert(clientDataBase64UrlString);
    assertAll(
            () -> assertThat(collectedClientData.getType()).isEqualTo(ClientDataType.GET),
            () -> assertThat(collectedClientData.getChallenge()).isEqualTo(new DefaultChallenge("tk31UH1ETGGTPj33OhOMzw")),
            () -> assertThat(collectedClientData.getOrigin()).isEqualTo(new Origin("http://localhost:8080"))
    );
}
 
Example #27
Source File: NullAttestationStatementValidatorTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void validate_RegistrationRequest_with_fido_u2f_attestation_statement_test() {
    FIDOU2FAuthenticatorAdaptor fidou2FAuthenticatorAdaptor = new FIDOU2FAuthenticatorAdaptor();
    ClientPlatform clientPlatform = new ClientPlatform(origin, fidou2FAuthenticatorAdaptor);
    String rpId = "example.com";
    Challenge challenge = new DefaultChallenge();
    PublicKeyCredentialParameters publicKeyCredentialParameters
            = new PublicKeyCredentialParameters(PublicKeyCredentialType.PUBLIC_KEY, COSEAlgorithmIdentifier.ES256);

    AuthenticatorSelectionCriteria authenticatorSelectionCriteria =
            new AuthenticatorSelectionCriteria(
                    AuthenticatorAttachment.CROSS_PLATFORM,
                    true,
                    UserVerificationRequirement.REQUIRED);

    AuthenticationExtensionsClientInputs<RegistrationExtensionClientInput<?>> extensions = new AuthenticationExtensionsClientInputs<>();
    PublicKeyCredentialCreationOptions credentialCreationOptions = new PublicKeyCredentialCreationOptions(
            new PublicKeyCredentialRpEntity(rpId, "valid.site.example.com"),
            new PublicKeyCredentialUserEntity(),
            challenge,
            Collections.singletonList(publicKeyCredentialParameters),
            null,
            Collections.emptyList(),
            authenticatorSelectionCriteria,
            AttestationConveyancePreference.DIRECT,
            extensions
    );
    AuthenticatorAttestationResponse registrationRequest = clientPlatform.create(credentialCreationOptions).getAuthenticatorResponse();
    Set<String> transports = authenticatorTransportConverter.convertSetToStringSet(registrationRequest.getTransports());
    ServerProperty serverProperty = new ServerProperty(origin, rpId, challenge, null);
    RegistrationRequest webAuthnRegistrationRequest =
            new RegistrationRequest(
                    registrationRequest.getAttestationObject(),
                    registrationRequest.getClientDataJSON(),
                    transports);
    RegistrationParameters registrationParameters =
            new RegistrationParameters(serverProperty, false);
    target.validate(webAuthnRegistrationRequest, registrationParameters);
}
 
Example #28
Source File: FIDOU2FAuthenticatorRegistrationValidationTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void validate_with_bad_challenge_test() {
    String rpId = "example.com";
    Challenge challenge = new DefaultChallenge();
    Challenge badChallenge = new DefaultChallenge();

    PublicKeyCredentialParameters publicKeyCredentialParameters
            = new PublicKeyCredentialParameters(PublicKeyCredentialType.PUBLIC_KEY, COSEAlgorithmIdentifier.ES256);
    PublicKeyCredentialCreationOptions credentialCreationOptions = new PublicKeyCredentialCreationOptions(
            new PublicKeyCredentialRpEntity(rpId, "example.com"),
            new PublicKeyCredentialUserEntity(),
            badChallenge,
            Collections.singletonList(publicKeyCredentialParameters)
    );

    AuthenticatorAttestationResponse authenticatorAttestationResponse = clientPlatform.create(credentialCreationOptions).getAuthenticatorResponse();

    Set<String> transports = authenticatorTransportConverter.convertSetToStringSet(authenticatorAttestationResponse.getTransports());
    ServerProperty serverProperty = new ServerProperty(origin, rpId, challenge, null);
    RegistrationRequest registrationRequest
            = new RegistrationRequest(
            authenticatorAttestationResponse.getAttestationObject(),
            authenticatorAttestationResponse.getClientDataJSON(),
            transports
    );
    RegistrationParameters registrationParameters
            = new RegistrationParameters(
            serverProperty,
            false,
            true,
            Collections.emptyList()
    );

    assertThrows(BadChallengeException.class,
            () -> target.validate(registrationRequest, registrationParameters)
    );
}
 
Example #29
Source File: FIDOU2FAuthenticatorRegistrationValidationTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void validate_with_bad_origin_test() {
    String rpId = "example.com";
    Challenge challenge = new DefaultChallenge();
    Origin badOrigin = new Origin("http://bad.origin.example.net");
    PublicKeyCredentialParameters publicKeyCredentialParameters
            = new PublicKeyCredentialParameters(PublicKeyCredentialType.PUBLIC_KEY, COSEAlgorithmIdentifier.ES256);
    PublicKeyCredentialCreationOptions credentialCreationOptions = new PublicKeyCredentialCreationOptions(
            new PublicKeyCredentialRpEntity(rpId, "example.com"),
            new PublicKeyCredentialUserEntity(),
            challenge,
            Collections.singletonList(publicKeyCredentialParameters)
    );

    clientPlatform.setOrigin(badOrigin); //bad origin
    AuthenticatorAttestationResponse authenticatorAttestationResponse = clientPlatform.create(credentialCreationOptions).getAuthenticatorResponse();

    Set<String> transports = authenticatorTransportConverter.convertSetToStringSet(authenticatorAttestationResponse.getTransports());
    ServerProperty serverProperty = new ServerProperty(origin, rpId, challenge, null);
    RegistrationRequest registrationRequest
            = new RegistrationRequest(
            authenticatorAttestationResponse.getAttestationObject(),
            authenticatorAttestationResponse.getClientDataJSON(),
            transports
    );
    RegistrationParameters registrationParameters
            = new RegistrationParameters(
            serverProperty,
            false,
            true,
            Collections.emptyList()
    );

    assertThrows(BadOriginException.class,
            () -> target.validate(registrationRequest, registrationParameters)
    );
}
 
Example #30
Source File: FIDOU2FAuthenticatorRegistrationValidationTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void validate_with_bad_rpId_test() {
    String rpId = "example.com";
    String badRpId = "example.net";
    Challenge challenge = new DefaultChallenge();
    PublicKeyCredentialParameters publicKeyCredentialParameters
            = new PublicKeyCredentialParameters(PublicKeyCredentialType.PUBLIC_KEY, COSEAlgorithmIdentifier.ES256);
    PublicKeyCredentialCreationOptions credentialCreationOptions = new PublicKeyCredentialCreationOptions(
            new PublicKeyCredentialRpEntity(badRpId, "example.com"),
            new PublicKeyCredentialUserEntity(),
            challenge,
            Collections.singletonList(publicKeyCredentialParameters)
    );
    AuthenticatorAttestationResponse authenticatorAttestationResponse = clientPlatform.create(credentialCreationOptions).getAuthenticatorResponse();
    Set<String> transports = authenticatorTransportConverter.convertSetToStringSet(authenticatorAttestationResponse.getTransports());
    ServerProperty serverProperty = new ServerProperty(origin, rpId, challenge, null);
    RegistrationRequest registrationRequest
            = new RegistrationRequest(
            authenticatorAttestationResponse.getAttestationObject(),
            authenticatorAttestationResponse.getClientDataJSON(),
            transports
    );
    RegistrationParameters registrationParameters
            = new RegistrationParameters(
            serverProperty,
            false,
            true,
            Collections.emptyList()
    );

    assertThrows(BadRpIdException.class,
            () -> target.validate(registrationRequest, registrationParameters)
    );
}