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

The following examples show how to use com.webauthn4j.data.client.challenge.Challenge. 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: HttpSessionChallengeRepositoryTest.java    From webauthn4j-spring-security with Apache License 2.0 6 votes vote down vote up
@Test
public void loadChallenge_test() {
    MockHttpSession session = new MockHttpSession();
    MockHttpServletRequest prevRequest = new MockHttpServletRequest();
    prevRequest.setSession(session);

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setSession(session);
    String attrName = ".test-challenge";

    target.setSessionAttributeName(attrName);
    Challenge challenge = target.generateChallenge();
    target.saveChallenge(challenge, prevRequest);
    Challenge loadedChallenge = target.loadChallenge(request);

    assertThat(loadedChallenge).isEqualTo(challenge);
}
 
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: PublicKeyCredentialCreationOptions.java    From webauthn4j with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("squid:S00107")
@JsonCreator
public PublicKeyCredentialCreationOptions(
        @JsonProperty("rp") PublicKeyCredentialRpEntity rp,
        @JsonProperty("user") PublicKeyCredentialUserEntity user,
        @JsonProperty("challenge") Challenge challenge,
        @JsonProperty("pubKeyCredParams") List<PublicKeyCredentialParameters> pubKeyCredParams,
        @JsonProperty("timeout") Long timeout,
        @JsonProperty("excludeCredentials") List<PublicKeyCredentialDescriptor> excludeCredentials,
        @JsonProperty("authenticatorSelection") AuthenticatorSelectionCriteria authenticatorSelection,
        @JsonProperty("attestation") AttestationConveyancePreference attestation,
        @JsonProperty("extensions") AuthenticationExtensionsClientInputs<RegistrationExtensionClientInput<?>> extensions) {
    this.rp = rp;
    this.user = user;
    this.challenge = challenge;
    this.pubKeyCredParams = CollectionUtil.unmodifiableList(pubKeyCredParams);
    this.timeout = timeout;
    this.excludeCredentials = CollectionUtil.unmodifiableList(excludeCredentials);
    this.authenticatorSelection = authenticatorSelection;
    this.attestation = attestation;
    this.extensions = extensions;
}
 
Example #4
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 #5
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 #6
Source File: RegistrationParametersTest.java    From webauthn4j with Apache License 2.0 6 votes vote down vote up
@Test
void equals_hashCode_test() {
    // Server properties
    Origin origin = null /* set origin */;
    String rpId = null /* set rpId */;
    Challenge challenge = null /* set challenge */;
    byte[] tokenBindingId = null /* set tokenBindingId */;
    ServerProperty serverProperty = new ServerProperty(origin, rpId, challenge, tokenBindingId);

    // expectations
    boolean userVerificationRequired = true;

    RegistrationParameters instanceA =
            new RegistrationParameters(
                    serverProperty,
                    userVerificationRequired
            );
    RegistrationParameters instanceB =
            new RegistrationParameters(
                    serverProperty,
                    userVerificationRequired
            );

    assertThat(instanceA).isEqualTo(instanceB);
    assertThat(instanceA).hasSameHashCodeAs(instanceB);
}
 
Example #7
Source File: OptionsResponse.java    From webauthn4j-spring-security with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("squid:S00107")
public OptionsResponse(
        PublicKeyCredentialRpEntity relyingParty,
        WebAuthnPublicKeyCredentialUserEntity user,
        Challenge challenge,
        List<PublicKeyCredentialParameters> pubKeyCredParams,
        Long registrationTimeout,
        Long authenticationTimeout,
        List<WebAuthnPublicKeyCredentialDescriptor> credentials,
        AuthenticationExtensionsClientInputs<RegistrationExtensionClientInput<?>> registrationExtensions,
        AuthenticationExtensionsClientInputs<AuthenticationExtensionClientInput<?>> authenticationExtensions,
        Parameters parameters) {
    super();

    this.relyingParty = relyingParty;
    this.user = user;
    this.challenge = challenge;
    this.pubKeyCredParams = CollectionUtil.unmodifiableList(pubKeyCredParams);
    this.registrationTimeout = registrationTimeout;
    this.authenticationTimeout = authenticationTimeout;
    this.credentials = CollectionUtil.unmodifiableList(credentials);
    this.registrationExtensions = registrationExtensions;
    this.authenticationExtensions = authenticationExtensions;
    this.parameters = parameters;
}
 
Example #8
Source File: AttestationOptions.java    From webauthn4j-spring-security with Apache License 2.0 6 votes vote down vote up
public AttestationOptions(
        PublicKeyCredentialRpEntity relyingParty,
        WebAuthnPublicKeyCredentialUserEntity user,
        Challenge challenge,
        List<PublicKeyCredentialParameters> pubKeyCredParams,
        Long registrationTimeout,
        List<String> credentials,
        AuthenticationExtensionsClientInputs<RegistrationExtensionClientInput<?>> registrationExtensions) {
    this.relyingParty = relyingParty;
    this.user = user;
    this.challenge = challenge;
    this.pubKeyCredParams = CollectionUtil.unmodifiableList(pubKeyCredParams);
    this.registrationTimeout = registrationTimeout;
    this.credentials = CollectionUtil.unmodifiableList(credentials);
    this.registrationExtensions = registrationExtensions;
}
 
Example #9
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 #10
Source File: OptionsProviderImplTest.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@Test
public void getAssertionOptions_with_challenge_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);

    OptionsProvider optionsProvider = new OptionsProviderImpl(userDetailsService, challengeRepository);
    optionsProvider.setRpId("example.com");
    optionsProvider.setRpName("rpName");

    AssertionOptions attestationOptions = optionsProvider.getAssertionOptions(mockRequest, "dummy", challenge);
    assertThat(attestationOptions.getRpId()).isEqualTo("example.com");
    assertThat(attestationOptions.getChallenge()).isEqualTo(challenge);
    assertThat(attestationOptions.getCredentials()).containsExactly(Base64UrlUtil.encodeToString(credentialId));

}
 
Example #11
Source File: WebAuthnJSONModule.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
public WebAuthnJSONModule(ObjectConverter objectConverter) {
    super("WebAuthnJSONModule");

    this.addDeserializer(Challenge.class, new ChallengeDeserializer());
    this.addDeserializer(ExtensionClientInput.class, new ExtensionClientInputDeserializer());
    this.addDeserializer(RegistrationExtensionClientInput.class, new RegistrationExtensionClientInputDeserializer());
    this.addDeserializer(AuthenticationExtensionClientInput.class, new AuthenticationExtensionClientInputDeserializer());
    this.addDeserializer(ExtensionClientOutput.class, new ExtensionClientOutputDeserializer());
    this.addDeserializer(UnknownExtensionClientInput.class, new UnknownExtensionClientInputDeserializer());
    this.addDeserializer(UnknownExtensionClientOutput.class, new UnknownExtensionClientOutputDeserializer());
    this.addDeserializer(JWS.class, new JWSDeserializer(objectConverter));
    this.addDeserializer(X509Certificate.class, new X509CertificateDeserializer());

    this.addSerializer(new ChallengeSerializer());
    this.addSerializer(new JWSSerializer());
    this.addSerializer(new X509CertificateSerializer());

    // client extension inputs
    this.registerSubtypes(new NamedType(CredentialPropertiesExtensionClientInput.class, CredentialPropertiesExtensionClientInput.ID));
    this.registerSubtypes(new NamedType(FIDOAppIDExtensionClientInput.class, FIDOAppIDExtensionClientInput.ID));

    // client extension outputs
    this.registerSubtypes(new NamedType(CredentialPropertiesExtensionClientOutput.class, CredentialPropertiesExtensionClientOutput.ID));
    this.registerSubtypes(new NamedType(FIDOAppIDExtensionClientOutput.class, FIDOAppIDExtensionClientOutput.ID));

}
 
Example #12
Source File: AuthenticationParametersTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void equals_hashCode_test() {
    // Server properties
    Origin origin = null /* set origin */;
    String rpId = null /* set rpId */;
    Challenge challenge = null /* set challenge */;
    byte[] tokenBindingId = null /* set tokenBindingId */;
    ServerProperty serverProperty = new ServerProperty(origin, rpId, challenge, tokenBindingId);

    Authenticator authenticator = null;

    // expectations
    boolean userVerificationRequired = true;
    boolean userPresenceRequired = true;
    List<String> expectedExtensionIds = Collections.emptyList();

    AuthenticationParameters instanceA =
            new AuthenticationParameters(
                    serverProperty,
                    authenticator,
                    userVerificationRequired,
                    userPresenceRequired,
                    expectedExtensionIds
            );
    AuthenticationParameters instanceB =
            new AuthenticationParameters(
                    serverProperty,
                    authenticator,
                    userVerificationRequired,
                    userPresenceRequired,
                    expectedExtensionIds
            );

    assertThat(instanceA).isEqualTo(instanceB);
    assertThat(instanceA).hasSameHashCodeAs(instanceB);

}
 
Example #13
Source File: PublicKeyCredentialRequestOptionsTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void getter_test() {
    String rpId = "example.com";
    long timeout = 0;
    Challenge challenge = new DefaultChallenge();
    byte[] credentialId = new byte[32];
    List<PublicKeyCredentialDescriptor> allowCredentials = Collections.singletonList(
            new PublicKeyCredentialDescriptor(
                    PublicKeyCredentialType.PUBLIC_KEY,
                    credentialId,
                    CollectionUtil.unmodifiableSet(AuthenticatorTransport.USB, AuthenticatorTransport.NFC, AuthenticatorTransport.BLE)
            )
    );

    PublicKeyCredentialRequestOptions credentialRequestOptions = new PublicKeyCredentialRequestOptions(
            challenge,
            timeout,
            rpId,
            allowCredentials,
            UserVerificationRequirement.DISCOURAGED,
            null
    );

    assertAll(
            () -> assertThat(credentialRequestOptions.getChallenge()).isEqualTo(challenge),
            () -> assertThat(credentialRequestOptions.getTimeout()).isEqualTo(timeout),
            () -> assertThat(credentialRequestOptions.getRpId()).isEqualTo(rpId),
            () -> assertThat(credentialRequestOptions.getAllowCredentials()).isEqualTo(allowCredentials),
            () -> assertThat(credentialRequestOptions.getUserVerification()).isEqualTo(UserVerificationRequirement.DISCOURAGED),
            () -> assertThat(credentialRequestOptions.getExtensions()).isNull()
    );
}
 
Example #14
Source File: CollectedClientDataTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void equals_hashCode_test() {
    Challenge challenge = TestDataUtil.createChallenge();
    CollectedClientData collectedClientDataA = TestDataUtil.createClientData(ClientDataType.GET, challenge);
    CollectedClientData collectedClientDataB = TestDataUtil.createClientData(ClientDataType.GET, challenge);
    assertAll(
            () -> assertThat(collectedClientDataA).isEqualTo(collectedClientDataB),
            () -> assertThat(collectedClientDataA).hasSameHashCodeAs(collectedClientDataB)
    );
}
 
Example #15
Source File: OptionsProviderImpl.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public AttestationOptions getAttestationOptions(HttpServletRequest request, String username, Challenge challenge) {

    WebAuthnPublicKeyCredentialUserEntity user;
    Collection<? extends Authenticator> authenticators;

    try {
        WebAuthnUserDetails userDetails = userDetailsService.loadUserByUsername(username);
        authenticators = userDetails.getAuthenticators();
        String userHandle = Base64UrlUtil.encodeToString(userDetails.getUserHandle());
        user = new WebAuthnPublicKeyCredentialUserEntity(userHandle, username);
    } catch (UsernameNotFoundException e) {
        authenticators = Collections.emptyList();
        user = null;
    }

    List<String> credentials = new ArrayList<>();
    for (Authenticator authenticator : authenticators) {
        String credentialId = Base64UrlUtil.encodeToString(authenticator.getAttestedCredentialData().getCredentialId());
        credentials.add(credentialId);
    }

    PublicKeyCredentialRpEntity relyingParty = new PublicKeyCredentialRpEntity(getEffectiveRpId(request), rpName, rpIcon);
    if (challenge == null) {
        challenge = challengeRepository.loadOrGenerateChallenge(request);
    } else {
        challengeRepository.saveChallenge(challenge, request);
    }

    return new AttestationOptions(relyingParty, user, challenge, pubKeyCredParams, registrationTimeout,
            credentials, registrationExtensions);
}
 
Example #16
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 #17
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 #18
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 #19
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 #20
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 #21
Source File: HttpSessionChallengeRepositoryTest.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@Test
public void loadOrGenerateChallenge_test_without_previous_request() {
    MockHttpServletRequest request = new MockHttpServletRequest();

    Challenge loadedChallenge = target.loadOrGenerateChallenge(request);

    assertThat(loadedChallenge).isNotNull();
}
 
Example #22
Source File: ServerEndpointFilterUtil.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
Challenge encodeUsername(Challenge challenge, String username) {
    UsernameEncodedChallengeEnvelope envelope = new UsernameEncodedChallengeEnvelope();
    envelope.setChallenge(challenge.getValue());
    envelope.setUsername(username);
    byte[] bytes = cborConverter.writeValueAsBytes(envelope);
    return new DefaultChallenge(bytes);
}
 
Example #23
Source File: ServerEndpointFilterUtil.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
String decodeUsername(Challenge challenge) {
    try {
        UsernameEncodedChallengeEnvelope envelope = cborConverter.readValue(challenge.getValue(), UsernameEncodedChallengeEnvelope.class);
        return envelope.getUsername();
    } catch (RuntimeException e) {
        return null;
    }
}
 
Example #24
Source File: ServerEndpointFilterUtil.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
Challenge encodeUserVerification(Challenge challenge, UserVerificationRequirement userVerification) {
    UserVerificationEncodedChallengeEnvelope envelope = new UserVerificationEncodedChallengeEnvelope();
    envelope.setChallenge(challenge.getValue());
    envelope.setUserVerification(userVerification);
    byte[] bytes = cborConverter.writeValueAsBytes(envelope);
    return new DefaultChallenge(bytes);
}
 
Example #25
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)
    );
}
 
Example #26
Source File: UserVerifyingAuthenticatorAuthenticationValidationTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
private AttestationObject createAttestationObject(String rpId, Challenge challenge) {
    AuthenticatorSelectionCriteria authenticatorSelectionCriteria =
            new AuthenticatorSelectionCriteria(
                    AuthenticatorAttachment.CROSS_PLATFORM,
                    true,
                    UserVerificationRequirement.REQUIRED);

    PublicKeyCredentialParameters publicKeyCredentialParameters = new PublicKeyCredentialParameters(PublicKeyCredentialType.PUBLIC_KEY, COSEAlgorithmIdentifier.ES256);

    PublicKeyCredentialUserEntity publicKeyCredentialUserEntity = new PublicKeyCredentialUserEntity();

    AuthenticationExtensionsClientInputs<RegistrationExtensionClientInput<?>> extensions = new AuthenticationExtensionsClientInputs<>();
    PublicKeyCredentialCreationOptions credentialCreationOptions
            = new PublicKeyCredentialCreationOptions(
            new PublicKeyCredentialRpEntity(rpId, "example.com"),
            publicKeyCredentialUserEntity,
            challenge,
            Collections.singletonList(publicKeyCredentialParameters),
            null,
            Collections.emptyList(),
            authenticatorSelectionCriteria,
            AttestationConveyancePreference.NONE,
            extensions
    );

    AuthenticatorAttestationResponse registrationRequest = clientPlatform.create(credentialCreationOptions).getAuthenticatorResponse();
    AttestationObjectConverter attestationObjectConverter = new AttestationObjectConverter(objectConverter);
    return attestationObjectConverter.convert(registrationRequest.getAttestationObject());
}
 
Example #27
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 #28
Source File: ChallengeAttrProcessor.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
private Challenge getChallenge(ITemplateContext context) {
    ApplicationContext applicationContext = SpringContextUtils.getApplicationContext(context);
    IWebContext webContext = (IWebContext) context;
    HttpServletRequest httpServletRequest = webContext.getRequest();
    ChallengeRepository challengeRepository = applicationContext.getBean(ChallengeRepository.class);
    Challenge challenge = challengeRepository.loadChallenge(httpServletRequest);
    if (challenge == null) {
        challenge = challengeRepository.generateChallenge();
        challengeRepository.saveChallenge(challenge, httpServletRequest);
    }
    return challenge;
}
 
Example #29
Source File: WebAuthnRegistrationContextValidatorSample.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
public void athenticationValidationSample() {
    // Client properties
    byte[] credentialId = null /* set credentialId */;
    byte[] clientDataJSON = null /* set clientDataJSON */;
    byte[] authenticatorData = null /* set authenticatorData */;
    byte[] signature = null /* set signature */;

    // Server properties
    Origin origin = null /* set origin */;
    String rpId = null /* set rpId */;
    Challenge challenge = null /* set challenge */;
    byte[] tokenBindingId = null /* set tokenBindingId */;
    ServerProperty serverProperty = new ServerProperty(origin, rpId, challenge, tokenBindingId);
    Authenticator authenticator = load(credentialId); // please load authenticator object persisted in the registration process in your manner
    boolean userVerificationRequired = true;

    AuthenticationRequest authenticationRequest =
            new AuthenticationRequest(
                    credentialId,
                    authenticatorData,
                    clientDataJSON,
                    signature
            );
    AuthenticationParameters authenticationParameters =
            new AuthenticationParameters(
                    serverProperty,
                    authenticator,
                    userVerificationRequired
            );

    WebAuthnManager webAuthnManager = WebAuthnManager.createNonStrictWebAuthnManager();

    AuthenticationData response = webAuthnManager.validate(authenticationRequest, authenticationParameters);

    // please update the counter of the authenticator record
    updateCounter(
            response.getCredentialId(),
            response.getAuthenticatorData().getSignCount()
    );
}
 
Example #30
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);
}