com.webauthn4j.data.RegistrationRequest Java Examples

The following examples show how to use com.webauthn4j.data.RegistrationRequest. 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: WebAuthnRegistrationRequestValidatorTest.java    From webauthn4j-spring-security with Apache License 2.0 6 votes vote down vote up
@Test(expected = BadAttestationStatementException.class)
public void validate_caught_exception_test() {
    WebAuthnRegistrationRequestValidator target = new WebAuthnRegistrationRequestValidator(
            webAuthnManager, serverPropertyProvider
    );
    when(webAuthnManager.validate(any(RegistrationRequest.class), any(RegistrationParameters.class))).thenThrow(new com.webauthn4j.validator.exception.BadAttestationStatementException("dummy"));

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
    mockHttpServletRequest.setScheme("https");
    mockHttpServletRequest.setServerName("example.com");
    mockHttpServletRequest.setServerPort(443);
    String clientDataBase64 = "clientDataBase64";
    String attestationObjectBase64 = "attestationObjectBase64";
    Set<String> transports = Collections.emptySet();
    String clientExtensionsJSON = "clientExtensionsJSON";

    target.validate(mockHttpServletRequest, clientDataBase64, attestationObjectBase64, transports, clientExtensionsJSON);

}
 
Example #2
Source File: WebAuthnRegistrationManager.java    From webauthn4j with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("squid:S1130")
public RegistrationData parse(RegistrationRequest registrationRequest) throws DataConversionException {

    byte[] clientDataBytes = registrationRequest.getClientDataJSON();
    byte[] attestationObjectBytes = registrationRequest.getAttestationObject();

    CollectedClientData collectedClientData = collectedClientDataConverter.convert(clientDataBytes);
    AttestationObject attestationObject = attestationObjectConverter.convert(attestationObjectBytes);
    Set<AuthenticatorTransport> transports = authenticatorTransportConverter.convertSet(registrationRequest.getTransports());
    AuthenticationExtensionsClientOutputs<RegistrationExtensionClientOutput<?>> clientExtensions =
            authenticationExtensionsClientOutputsConverter.convert(registrationRequest.getClientExtensionsJSON());

    return new RegistrationData(
            attestationObject,
            attestationObjectBytes,
            collectedClientData,
            clientDataBytes,
            clientExtensions,
            transports
    );

}
 
Example #3
Source File: WebAuthnRegistrationRequestValidator.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
public WebAuthnRegistrationRequestValidationResponse validate(HttpServletRequest httpServletRequest,
                                                              String clientDataBase64url,
                                                              String attestationObjectBase64url,
                                                              Set<String> transports,
                                                              String clientExtensionsJSON
) {
    Assert.notNull(httpServletRequest, "httpServletRequest must not be null");
    Assert.hasText(clientDataBase64url, "clientDataBase64url must have text");
    Assert.hasText(attestationObjectBase64url, "attestationObjectBase64url must have text");
    if (transports != null) {
        transports.forEach(transport -> Assert.hasText(transport, "each transport must have text"));
    }

    RegistrationRequest webAuthnRegistrationRequest =
            createRegistrationRequest(clientDataBase64url, attestationObjectBase64url, transports, clientExtensionsJSON);
    RegistrationParameters webAuthnRegistrationParameters =
            createRegistrationParameters(httpServletRequest);

    try {
        RegistrationData response = webAuthnManager.validate(webAuthnRegistrationRequest, webAuthnRegistrationParameters);
        return new WebAuthnRegistrationRequestValidationResponse(
                response.getCollectedClientData(),
                response.getAttestationObject(),
                response.getClientExtensions());
    } catch (WebAuthnException e) {
        throw ExceptionUtil.wrapWithAuthenticationException(e);
    }
}
 
Example #4
Source File: WebAuthnRegistrationRequestValidator.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
RegistrationRequest createRegistrationRequest(String clientDataBase64,
                                              String attestationObjectBase64,
                                              Set<String> transports,
                                              String clientExtensionsJSON) {

    byte[] clientDataBytes = Base64UrlUtil.decode(clientDataBase64);
    byte[] attestationObjectBytes = Base64UrlUtil.decode(attestationObjectBase64);

    return new RegistrationRequest(
            attestationObjectBytes,
            clientDataBytes,
            clientExtensionsJSON,
            transports
    );
}
 
Example #5
Source File: WebAuthnRegistrationRequestValidatorTest.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@Test
public void validate_test() {
    WebAuthnRegistrationRequestValidator target = new WebAuthnRegistrationRequestValidator(
            webAuthnManager, serverPropertyProvider
    );

    ServerProperty serverProperty = mock(ServerProperty.class);
    when(serverPropertyProvider.provide(any())).thenReturn(serverProperty);

    CollectedClientData collectedClientData = mock(CollectedClientData.class);
    AttestationObject attestationObject = mock(AttestationObject.class);
    AuthenticationExtensionsClientOutputs<RegistrationExtensionClientOutput<?>> clientExtensionOutputs = new AuthenticationExtensionsClientOutputs<>();
    when(webAuthnManager.validate(any(RegistrationRequest.class), any(RegistrationParameters.class))).thenReturn(
            new RegistrationData(attestationObject, null, collectedClientData, null, clientExtensionOutputs, null));

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
    mockHttpServletRequest.setScheme("https");
    mockHttpServletRequest.setServerName("example.com");
    mockHttpServletRequest.setServerPort(443);
    String clientDataBase64 = "clientDataBase64";
    String attestationObjectBase64 = "attestationObjectBase64";
    Set<String> transports = Collections.emptySet();
    String clientExtensionsJSON = "clientExtensionsJSON";

    target.validate(mockHttpServletRequest, clientDataBase64, attestationObjectBase64, transports, clientExtensionsJSON);

    ArgumentCaptor<RegistrationRequest> registrationRequestArgumentCaptor = ArgumentCaptor.forClass(RegistrationRequest.class);
    ArgumentCaptor<RegistrationParameters> registrationParametersArgumentCaptor = ArgumentCaptor.forClass(RegistrationParameters.class);
    verify(webAuthnManager).validate(registrationRequestArgumentCaptor.capture(), registrationParametersArgumentCaptor.capture());
    RegistrationRequest registrationRequest = registrationRequestArgumentCaptor.getValue();
    RegistrationParameters registrationParameters = registrationParametersArgumentCaptor.getValue();

    assertThat(registrationRequest.getClientDataJSON()).isEqualTo(Base64UrlUtil.decode(clientDataBase64));
    assertThat(registrationRequest.getAttestationObject()).isEqualTo(Base64UrlUtil.decode(attestationObjectBase64));
    assertThat(registrationRequest.getClientExtensionsJSON()).isEqualTo(clientExtensionsJSON);
    assertThat(registrationParameters.getServerProperty()).isEqualTo(serverProperty);
    assertThat(registrationParameters.getExpectedExtensionIds()).isEqualTo(target.getExpectedRegistrationExtensionIds());
}
 
Example #6
Source File: WebAuthnRegistrationRequestValidatorTest.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@Test
public void validate_with_transports_null_test() {
    WebAuthnRegistrationRequestValidator target = new WebAuthnRegistrationRequestValidator(
            webAuthnManager, serverPropertyProvider
    );

    ServerProperty serverProperty = mock(ServerProperty.class);
    when(serverPropertyProvider.provide(any())).thenReturn(serverProperty);

    CollectedClientData collectedClientData = mock(CollectedClientData.class);
    AttestationObject attestationObject = mock(AttestationObject.class);
    AuthenticationExtensionsClientOutputs<RegistrationExtensionClientOutput<?>> clientExtensionOutputs = new AuthenticationExtensionsClientOutputs<>();
    when(webAuthnManager.validate(any(RegistrationRequest.class), any(RegistrationParameters.class))).thenReturn(
            new RegistrationData(attestationObject, null, collectedClientData, null, clientExtensionOutputs, null));

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
    mockHttpServletRequest.setScheme("https");
    mockHttpServletRequest.setServerName("example.com");
    mockHttpServletRequest.setServerPort(443);
    String clientDataBase64 = "clientDataBase64";
    String attestationObjectBase64 = "attestationObjectBase64";
    String clientExtensionsJSON = "clientExtensionsJSON";

    target.validate(mockHttpServletRequest, clientDataBase64, attestationObjectBase64, null, clientExtensionsJSON);

    ArgumentCaptor<RegistrationRequest> registrationRequestArgumentCaptor = ArgumentCaptor.forClass(RegistrationRequest.class);
    ArgumentCaptor<RegistrationParameters> registrationParametersArgumentCaptor = ArgumentCaptor.forClass(RegistrationParameters.class);
    verify(webAuthnManager).validate(registrationRequestArgumentCaptor.capture(), registrationParametersArgumentCaptor.capture());
    RegistrationRequest registrationRequest = registrationRequestArgumentCaptor.getValue();
    RegistrationParameters registrationParameters = registrationParametersArgumentCaptor.getValue();

    assertThat(registrationRequest.getClientDataJSON()).isEqualTo(Base64UrlUtil.decode(clientDataBase64));
    assertThat(registrationRequest.getAttestationObject()).isEqualTo(Base64UrlUtil.decode(attestationObjectBase64));
    assertThat(registrationRequest.getClientExtensionsJSON()).isEqualTo(clientExtensionsJSON);
    assertThat(registrationParameters.getServerProperty()).isEqualTo(serverProperty);
    assertThat(registrationParameters.getExpectedExtensionIds()).isEqualTo(target.getExpectedRegistrationExtensionIds());
}
 
Example #7
Source File: WebAuthnRegistrationManager.java    From webauthn4j with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("squid:S1130")
public RegistrationData validate(RegistrationRequest registrationRequest, RegistrationParameters registrationParameters) throws DataConversionException, ValidationException {
    RegistrationData registrationData = parse(registrationRequest);
    registrationDataValidator.validate(registrationData, registrationParameters);
    return registrationData;
}
 
Example #8
Source File: WebAuthnRegister.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void processAction(RequiredActionContext context) {

    MultivaluedMap<String, String> params = context.getHttpRequest().getDecodedFormParameters();

    String isSetRetry = params.getFirst(WebAuthnConstants.IS_SET_RETRY);
    if (isSetRetry != null && !isSetRetry.isEmpty()) {
        requiredActionChallenge(context);
        return;
    }

    context.getEvent().detail(Details.CREDENTIAL_TYPE, getCredentialType());

    // receive error from navigator.credentials.create()
    String errorMsgFromWebAuthnApi = params.getFirst(WebAuthnConstants.ERROR);
    if (errorMsgFromWebAuthnApi != null && !errorMsgFromWebAuthnApi.isEmpty()) {
        setErrorResponse(context, WEBAUTHN_ERROR_REGISTER_VERIFICATION, errorMsgFromWebAuthnApi);
        return;
    }

    WebAuthnPolicy policy = getWebAuthnPolicy(context);
    String rpId = policy.getRpId();
    if (rpId == null || rpId.isEmpty()) rpId =  context.getUriInfo().getBaseUri().getHost();
    String label = params.getFirst(WebAuthnConstants.AUTHENTICATOR_LABEL);
    byte[] clientDataJSON = Base64.getUrlDecoder().decode(params.getFirst(WebAuthnConstants.CLIENT_DATA_JSON));
    byte[] attestationObject = Base64.getUrlDecoder().decode(params.getFirst(WebAuthnConstants.ATTESTATION_OBJECT));

    String publicKeyCredentialId = params.getFirst(WebAuthnConstants.PUBLIC_KEY_CREDENTIAL_ID);

    Origin origin = new Origin(UriUtils.getOrigin(context.getUriInfo().getBaseUri()));
    Challenge challenge = new DefaultChallenge(context.getAuthenticationSession().getAuthNote(WebAuthnConstants.AUTH_CHALLENGE_NOTE));
    ServerProperty serverProperty = new ServerProperty(origin, rpId, challenge, null);
    // check User Verification by considering a malicious user might modify the result of calling WebAuthn API
    boolean isUserVerificationRequired = policy.getUserVerificationRequirement().equals(WebAuthnConstants.OPTION_REQUIRED);

    RegistrationRequest registrationRequest = new RegistrationRequest(attestationObject, clientDataJSON);
    RegistrationParameters registrationParameters = new RegistrationParameters(serverProperty, isUserVerificationRequired);

    WebAuthnRegistrationManager webAuthnRegistrationManager = createWebAuthnRegistrationManager();
    try {
        // parse
        RegistrationData registrationData = webAuthnRegistrationManager.parse(registrationRequest);
        // validate
        webAuthnRegistrationManager.validate(registrationData, registrationParameters);

        showInfoAfterWebAuthnApiCreate(registrationData);

        checkAcceptedAuthenticator(registrationData, policy);

        WebAuthnCredentialModelInput credential = new WebAuthnCredentialModelInput(getCredentialType());

        credential.setAttestedCredentialData(registrationData.getAttestationObject().getAuthenticatorData().getAttestedCredentialData());
        credential.setCount(registrationData.getAttestationObject().getAuthenticatorData().getSignCount());
        credential.setAttestationStatementFormat(registrationData.getAttestationObject().getFormat());

        // Save new webAuthn credential
        WebAuthnCredentialProvider webAuthnCredProvider = (WebAuthnCredentialProvider) this.session.getProvider(CredentialProvider.class, getCredentialProviderId());
        WebAuthnCredentialModel newCredentialModel = webAuthnCredProvider.getCredentialModelFromCredentialInput(credential, label);

        webAuthnCredProvider.createCredential(context.getRealm(), context.getUser(), newCredentialModel);

        String aaguid = newCredentialModel.getWebAuthnCredentialData().getAaguid();
        logger.debugv("WebAuthn credential registration success for user {0}. credentialType = {1}, publicKeyCredentialId = {2}, publicKeyCredentialLabel = {3}, publicKeyCredentialAAGUID = {4}",
                context.getUser().getUsername(), getCredentialType(), publicKeyCredentialId, label, aaguid);
        webAuthnCredProvider.dumpCredentialModel(newCredentialModel, credential);

        context.getEvent()
            .detail(WebAuthnConstants.PUBKEY_CRED_ID_ATTR, publicKeyCredentialId)
            .detail(WebAuthnConstants.PUBKEY_CRED_LABEL_ATTR, label)
            .detail(WebAuthnConstants.PUBKEY_CRED_AAGUID_ATTR, aaguid);
        context.success();
    } catch (WebAuthnException wae) {
        if (logger.isDebugEnabled()) logger.debug(wae.getMessage(), wae);
        setErrorResponse(context, WEBAUTHN_ERROR_REGISTRATION, wae.getMessage());
        return;
    } catch (Exception e) {
        if (logger.isDebugEnabled()) logger.debug(e.getMessage(), e);
        setErrorResponse(context, WEBAUTHN_ERROR_REGISTRATION, e.getMessage());
        return;
    }
}