Java Code Examples for com.webauthn4j.util.Base64UrlUtil#encodeToString()

The following examples show how to use com.webauthn4j.util.Base64UrlUtil#encodeToString() . 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: TokenBindingTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void constructor_test() {
    TokenBinding tokenBindingA = new TokenBinding(TokenBindingStatus.SUPPORTED, Base64UrlUtil.encodeToString(new byte[]{0x01, 0x23, 0x45}));
    TokenBinding tokenBindingB = new TokenBinding(TokenBindingStatus.SUPPORTED, new byte[]{0x01, 0x23, 0x45});

    assertThat(tokenBindingA).isEqualTo(tokenBindingB);
}
 
Example 2
Source File: JWSFactory.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
public <T extends Serializable> JWS<T> create(JWSHeader header, T payload, PrivateKey privateKey) {
    String headerString = Base64UrlUtil.encodeToString(jsonConverter.writeValueAsString(header).getBytes(StandardCharsets.UTF_8));
    String payloadString = Base64UrlUtil.encodeToString(jsonConverter.writeValueAsString(payload).getBytes(StandardCharsets.UTF_8));
    String signedData = headerString + "." + payloadString;
    Signature signatureObj = SignatureUtil.createSignature(header.getAlg().getJcaName());
    try {
        signatureObj.initSign(privateKey);
        signatureObj.update(signedData.getBytes());
        byte[] derSignature = signatureObj.sign();
        byte[] jwsSignature = JWSSignatureUtil.convertDerSignatureToJwsSignature(derSignature);
        return new JWS<>(header, headerString, payload, payloadString, jwsSignature);
    } catch (InvalidKeyException | SignatureException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 3
Source File: CollectedClientDataConverterTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void convertToString_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);
    String result = target.convertToBase64UrlString(collectedClientData);
    //noinspection SpellCheckingInspection
    assertThat(result).isEqualTo("eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoidGszMVVIMUVUR0dUUGozM09oT016dyIsIm9yaWdpbiI6Imh0dHA6Ly9sb2NhbGhvc3Q6ODA4MCIsInRva2VuQmluZGluZyI6eyJzdGF0dXMiOiJub3Qtc3VwcG9ydGVkIn19");
}
 
Example 4
Source File: TokenBinding.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
public TokenBinding(TokenBindingStatus status, byte[] id) {
    this.status = status;
    if (id == null) {
        this.id = null;
    } else {
        this.id = Base64UrlUtil.encodeToString(id);
    }
}
 
Example 5
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 6
Source File: OptionsProviderImpl.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
public AssertionOptions getAssertionOptions(HttpServletRequest request, String username, Challenge challenge) {

        Collection<? extends Authenticator> authenticators;
        try {
            WebAuthnUserDetails userDetails = userDetailsService.loadUserByUsername(username);
            authenticators = userDetails.getAuthenticators();
        } catch (UsernameNotFoundException e) {
            authenticators = Collections.emptyList();
        }

        String effectiveRpId = getEffectiveRpId(request);

        List<String> credentials = new ArrayList<>();
        for (Authenticator authenticator : authenticators) {
            String credentialId = Base64UrlUtil.encodeToString(authenticator.getAttestedCredentialData().getCredentialId());
            credentials.add(credentialId);
        }
        if (challenge == null) {
            challenge = challengeRepository.loadOrGenerateChallenge(request);
        } else {
            challengeRepository.saveChallenge(challenge, request);
        }
        Parameters parameters
                = new Parameters(usernameParameter, passwordParameter,
                credentialIdParameter, clientDataJSONParameter, authenticatorDataParameter, signatureParameter, clientExtensionsJSONParameter);

        return new AssertionOptions(challenge, authenticationTimeout, effectiveRpId, credentials, authenticationExtensions, parameters);
    }
 
Example 7
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 8
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 9
Source File: RegistrationValidationTest.java    From webauthn4j-spring-security with Apache License 2.0 4 votes vote down vote up
@Test
public void validate_test() {
    ServerProperty serverProperty = new ServerProperty(origin, rpId, challenge, null);
    when(serverPropertyProvider.provide(any())).thenReturn(serverProperty);


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

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

    PublicKeyCredentialUserEntity publicKeyCredentialUserEntity = new PublicKeyCredentialUserEntity();

    PublicKeyCredentialCreationOptions credentialCreationOptions = new PublicKeyCredentialCreationOptions(
            new PublicKeyCredentialRpEntity(rpId, "example.com"),
            publicKeyCredentialUserEntity,
            challenge,
            Collections.singletonList(publicKeyCredentialParameters),
            null,
            null,
            authenticatorSelectionCriteria,
            AttestationConveyancePreference.NONE,
            null
    );

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

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

    String clientDataBase64 = Base64UrlUtil.encodeToString(registrationRequest.getClientDataJSON());
    String attestationObjectBase64 = Base64UrlUtil.encodeToString(registrationRequest.getAttestationObject());
    Set<String> transports = Collections.emptySet();
    String clientExtensionsJSON = null;

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

    assertThat(response.getAttestationObject()).isNotNull();
    assertThat(response.getCollectedClientData()).isNotNull();
    assertThat(response.getRegistrationExtensionsClientOutputs()).isNull();
}
 
Example 10
Source File: JWS.java    From webauthn4j with Apache License 2.0 4 votes vote down vote up
@Override
public String toString() {
    return headerString + "." + payloadString + "." + Base64UrlUtil.encodeToString(signature);
}
 
Example 11
Source File: AppSpecificMapper.java    From webauthn4j-spring-security with Apache License 2.0 4 votes vote down vote up
public String mapToBase64Url(byte[] bytes) {
    return Base64UrlUtil.encodeToString(bytes);
}
 
Example 12
Source File: COSEKeyConverter.java    From webauthn4j-spring-security with Apache License 2.0 4 votes vote down vote up
@Override
public String convertToDatabaseColumn(COSEKey attribute) {
    return Base64UrlUtil.encodeToString(cborConverter.writeValueAsBytes(attribute));
}
 
Example 13
Source File: CredentialPublicKeyConverter.java    From keycloak-webauthn-authenticator with Apache License 2.0 4 votes vote down vote up
@Override
public String convertToDatabaseColumn(CredentialPublicKey credentialPublicKey) {
    return Base64UrlUtil.encodeToString(converter.writeValueAsBytes(credentialPublicKey));
}
 
Example 14
Source File: AttestationStatementConverter.java    From webauthn4j-spring-security with Apache License 2.0 4 votes vote down vote up
@Override
public String convertToDatabaseColumn(AttestationStatement attribute) {
    AttestationStatementSerializationContainer container = new AttestationStatementSerializationContainer(attribute);
    return Base64UrlUtil.encodeToString(cborConverter.writeValueAsBytes(container));
}
 
Example 15
Source File: AuthenticatorExtensionsConverter.java    From webauthn4j-spring-security with Apache License 2.0 4 votes vote down vote up
@Override
public String convertToDatabaseColumn(Map<String, RegistrationExtensionAuthenticatorOutput<?>> attribute) {
    return Base64UrlUtil.encodeToString(cborConverter.writeValueAsBytes(attribute));
}
 
Example 16
Source File: JWSFactory.java    From webauthn4j with Apache License 2.0 4 votes vote down vote up
public <T extends Serializable> JWS<T> create(JWSHeader header, T payload, byte[] signature) {
    String headerString = Base64UrlUtil.encodeToString(jsonConverter.writeValueAsString(header).getBytes(StandardCharsets.UTF_8));
    String payloadString = Base64UrlUtil.encodeToString(jsonConverter.writeValueAsString(payload).getBytes(StandardCharsets.UTF_8));
    return new JWS<>(header, headerString, payload, payloadString, signature);
}
 
Example 17
Source File: ChallengeSerializer.java    From webauthn4j with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void serialize(Challenge value, JsonGenerator gen, SerializerProvider provider) throws IOException {
    String challenge = Base64UrlUtil.encodeToString(value.getValue());
    gen.writeString(challenge);
}
 
Example 18
Source File: PublicKeyCredential.java    From webauthn4j with Apache License 2.0 4 votes vote down vote up
public PublicKeyCredential(byte[] credentialId, R authenticatorResponse, AuthenticationExtensionsClientOutputs<E> clientExtensionResults) {
    this.id = Base64UrlUtil.encodeToString(credentialId);
    this.rawId = credentialId;
    this.authenticatorResponse = authenticatorResponse;
    this.clientExtensionResults = clientExtensionResults;
}
 
Example 19
Source File: CollectedClientDataConverter.java    From webauthn4j with Apache License 2.0 2 votes vote down vote up
/**
 * Converts from a {@link CollectedClientData} to base64 url {@link String}.
 *
 * @param source the source object to convert
 * @return the converted byte array
 */
public String convertToBase64UrlString(CollectedClientData source) {
    byte[] bytes = convertToBytes(source);
    return Base64UrlUtil.encodeToString(bytes);
}
 
Example 20
Source File: AttestationObjectConverter.java    From webauthn4j with Apache License 2.0 2 votes vote down vote up
/**
 * Converts from a {@link AttestationObject} to {@link String}.
 *
 * @param source the source object to convert
 * @return the converted byte array
 */
public String convertToBase64urlString(AttestationObject source) {
    byte[] bytes = convertToBytes(source);
    return Base64UrlUtil.encodeToString(bytes);
}