com.webauthn4j.authenticator.Authenticator Java Examples

The following examples show how to use com.webauthn4j.authenticator.Authenticator. 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: WebAuthnAuthenticationProviderTest.java    From webauthn4j-spring-security with Apache License 2.0 6 votes vote down vote up
@Test(expected = LockedException.class)
public void userDetailsChecker_check_with_locked_userDetails_test() {
    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_ADMIN");
    Authenticator authenticator = new AuthenticatorImpl(null, null, 0);
    WebAuthnUserDetailsImpl userDetails = new WebAuthnUserDetailsImpl(
            new byte[0],
            "dummy",
            "dummy",
            Collections.singletonList(authenticator),
            true,
            true,
            true,
            true,
            false,
            Collections.singletonList(grantedAuthority));
    authenticationProvider.getPreAuthenticationChecks().check(userDetails);
}
 
Example #2
Source File: WebAuthnAuthenticationProviderTest.java    From webauthn4j-spring-security with Apache License 2.0 6 votes vote down vote up
@Test(expected = CredentialsExpiredException.class)
public void userDetailsChecker_check_with_credentials_expired_userDetails_test() {
    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_ADMIN");
    Authenticator authenticator = new AuthenticatorImpl(null, null, 0);
    WebAuthnUserDetailsImpl userDetails = new WebAuthnUserDetailsImpl(
            new byte[0],
            "dummy",
            "dummy",
            Collections.singletonList(authenticator),
            true,
            true,
            true,
            false,
            true,
            Collections.singletonList(grantedAuthority));
    authenticationProvider.getPostAuthenticationChecks().check(userDetails);
}
 
Example #3
Source File: WebAuthnAuthenticationProviderTest.java    From webauthn4j-spring-security with Apache License 2.0 6 votes vote down vote up
@Test(expected = AccountExpiredException.class)
public void userDetailsChecker_check_with_expired_userDetails_test() {
    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_ADMIN");
    Authenticator authenticator = new AuthenticatorImpl(null, null, 0);
    WebAuthnUserDetailsImpl userDetails = new WebAuthnUserDetailsImpl(
            new byte[0],
            "dummy",
            "dummy",
            Collections.singletonList(authenticator),
            true,
            true,
            false,
            true,
            true,
            Collections.singletonList(grantedAuthority));
    authenticationProvider.getPreAuthenticationChecks().check(userDetails);
}
 
Example #4
Source File: WebAuthnAuthenticationProviderTest.java    From webauthn4j-spring-security with Apache License 2.0 6 votes vote down vote up
@Test(expected = DisabledException.class)
public void userDetailsChecker_check_with_disabled_userDetails_test() {
    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_ADMIN");
    Authenticator authenticator = new AuthenticatorImpl(null, null, 0);
    WebAuthnUserDetailsImpl userDetails = new WebAuthnUserDetailsImpl(
            new byte[0],
            "dummy",
            "dummy",
            Collections.singletonList(authenticator),
            true,
            false,
            true,
            true,
            true,
            Collections.singletonList(grantedAuthority));
    authenticationProvider.getPreAuthenticationChecks().check(userDetails);
}
 
Example #5
Source File: AuthenticationObject.java    From webauthn4j with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("squid:S00107")
public AuthenticationObject(
        byte[] credentialId,
        AuthenticatorData<AuthenticationExtensionAuthenticatorOutput<?>> authenticatorData,
        byte[] authenticatorDataBytes,
        CollectedClientData collectedClientData,
        byte[] collectedClientDataBytes,
        AuthenticationExtensionsClientOutputs<AuthenticationExtensionClientOutput<?>> clientExtensions,
        ServerProperty serverProperty,
        Authenticator authenticator) {
    this.credentialId = ArrayUtil.clone(credentialId);
    this.authenticatorData = authenticatorData;
    this.authenticatorDataBytes = ArrayUtil.clone(authenticatorDataBytes);
    this.collectedClientData = collectedClientData;
    this.collectedClientDataBytes = ArrayUtil.clone(collectedClientDataBytes);
    this.clientExtensions = clientExtensions;
    this.serverProperty = serverProperty;
    this.authenticator = authenticator;
}
 
Example #6
Source File: WebAuthnUserDetailsImplTest.java    From webauthn4j-spring-security with Apache License 2.0 6 votes vote down vote up
@Test
public void getter_setter_test() {
    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_ADMIN");
    Authenticator authenticator = new AuthenticatorImpl(null, null, 0);
    WebAuthnUserDetailsImpl userDetails = new WebAuthnUserDetailsImpl(
            new byte[32],
            "dummy",
            "dummy",
            Collections.singletonList(authenticator),
            Collections.singletonList(grantedAuthority));

    userDetails.setSingleFactorAuthenticationAllowed(true);
    assertThat(userDetails.getUserHandle()).isEqualTo(new byte[32]);
    assertThat(userDetails.isSingleFactorAuthenticationAllowed()).isTrue();
    assertThat(userDetails.getAuthenticators()).isEqualTo(Collections.singletonList(authenticator));
}
 
Example #7
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 #8
Source File: WebAuthnAuthenticationProvider.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
void doAuthenticate(WebAuthnAssertionAuthenticationToken authenticationToken, Authenticator authenticator, WebAuthnUserDetails user) {

        WebAuthnAuthenticationRequest credentials = authenticationToken.getCredentials();

        boolean userVerificationRequired = isUserVerificationRequired(user, credentials);

        AuthenticationRequest authenticationRequest = new AuthenticationRequest(
                credentials.getCredentialId(),
                credentials.getAuthenticatorData(),
                credentials.getClientDataJSON(),
                credentials.getClientExtensionsJSON(),
                credentials.getSignature()
        );
        AuthenticationParameters authenticationParameters = new AuthenticationParameters(
                credentials.getServerProperty(),
                authenticator,
                userVerificationRequired,
                credentials.isUserPresenceRequired(),
                credentials.getExpectedAuthenticationExtensionIds()
        );

        try {
            webAuthnManager.validate(authenticationRequest, authenticationParameters);
        } catch (WebAuthnException e) {
            throw ExceptionUtil.wrapWithAuthenticationException(e);
        }

    }
 
Example #9
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 #10
Source File: AuthenticationParametersTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void constructor_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;

    AuthenticationParameters authenticationParameters =
            new AuthenticationParameters(
                    serverProperty,
                    authenticator,
                    userVerificationRequired
            );

    assertThat(authenticationParameters.getServerProperty()).isEqualTo(serverProperty);
    assertThat(authenticationParameters.getAuthenticator()).isEqualTo(authenticator);
    assertThat(authenticationParameters.isUserVerificationRequired()).isEqualTo(userVerificationRequired);
    assertThat(authenticationParameters.isUserPresenceRequired()).isTrue();
    assertThat(authenticationParameters.getExpectedExtensionIds()).isNull();
}
 
Example #11
Source File: AuthenticationParameters.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
public AuthenticationParameters(
        ServerProperty serverProperty,
        Authenticator authenticator,
        boolean userVerificationRequired) {
    this(
            serverProperty,
            authenticator,
            userVerificationRequired,
            true
    );
}
 
Example #12
Source File: AuthenticationParameters.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
public AuthenticationParameters(
        ServerProperty serverProperty,
        Authenticator authenticator,
        boolean userVerificationRequired,
        boolean userPresenceRequired) {
    this(
            serverProperty,
            authenticator,
            userVerificationRequired,
            userPresenceRequired,
            null
    );
}
 
Example #13
Source File: AuthenticationParameters.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
public AuthenticationParameters(
        ServerProperty serverProperty,
        Authenticator authenticator,
        boolean userVerificationRequired,
        boolean userPresenceRequired,
        List<String> expectedExtensionIds) {
    this.serverProperty = serverProperty;
    this.authenticator = authenticator;
    this.userVerificationRequired = userVerificationRequired;
    this.userPresenceRequired = userPresenceRequired;
    this.expectedExtensionIds = CollectionUtil.unmodifiableList(expectedExtensionIds);
}
 
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: AuthenticationObjectTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void getter_test() {

    byte[] credentialId = new byte[32];
    CollectedClientData clientData = TestDataUtil.createClientData(ClientDataType.CREATE);
    byte[] clientDataBytes = new CollectedClientDataConverter(objectConverter).convertToBytes(clientData);
    AuthenticatorData<AuthenticationExtensionAuthenticatorOutput<?>> authenticatorData = TestDataUtil.createAuthenticatorData();
    byte[] authenticatorDataBytes = new AuthenticatorDataConverter(objectConverter).convert(authenticatorData);
    AuthenticationExtensionsClientOutputs<AuthenticationExtensionClientOutput<?>> clientExtensions = new AuthenticationExtensionsClientOutputs<>();
    ServerProperty serverProperty = TestDataUtil.createServerProperty();
    Authenticator authenticator = TestDataUtil.createAuthenticator();
    AuthenticationObject authenticationObject = new AuthenticationObject(
            credentialId,
            authenticatorData,
            authenticatorDataBytes,
            clientData,
            clientDataBytes,
            clientExtensions,
            serverProperty,
            authenticator
    );

    assertAll(
            () -> assertThat(authenticationObject.getCredentialId()).isEqualTo(credentialId),
            () -> assertThat(authenticationObject.getCollectedClientData()).isEqualTo(clientData),
            () -> assertThat(authenticationObject.getCollectedClientDataBytes()).isEqualTo(clientDataBytes),
            () -> assertThat(authenticationObject.getAuthenticatorData()).isEqualTo(authenticatorData),
            () -> assertThat(authenticationObject.getAuthenticatorDataBytes()).isEqualTo(authenticatorDataBytes),
            () -> assertThat(authenticationObject.getClientExtensions()).isEqualTo(clientExtensions),
            () -> assertThat(authenticationObject.getServerProperty()).isEqualTo(serverProperty),
            () -> assertThat(authenticationObject.getAuthenticator()).isEqualTo(authenticator)
    );
}
 
Example #16
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 #17
Source File: WebAuthnUserDetailsImpl.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("squid:S00107")
public WebAuthnUserDetailsImpl(byte[] userHandle, String username, String password, List<Authenticator> authenticators, boolean singleFactorAuthenticationAllowed,
                               boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked,
                               Collection<? extends GrantedAuthority> authorities) {
    super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
    this.userHandle = userHandle;
    this.authenticators = authenticators;
    this.singleFactorAuthenticationAllowed = singleFactorAuthenticationAllowed;
}
 
Example #18
Source File: WebAuthnAuthenticationProviderTest.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@Test
public void userDetailsChecker_check_test() {
    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_ADMIN");
    Authenticator authenticator = new AuthenticatorImpl(null, null, 0);
    WebAuthnUserDetailsImpl userDetails = new WebAuthnUserDetailsImpl(
            new byte[0],
            "dummy",
            "dummy",
            Collections.singletonList(authenticator),
            Collections.singletonList(grantedAuthority));
    authenticationProvider.getPreAuthenticationChecks().check(userDetails);
}
 
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_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");
    optionsProvider.setRpIcon("data://dummy");

    AttestationOptions attestationOptions = optionsProvider.getAttestationOptions(mockRequest, "dummy", challenge);
    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: 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 #21
Source File: UserManagerImpl.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@Override
public void addAuthenticator(String username, Authenticator authenticator) {
    UserEntity userEntity = userEntityRepository.findOneByEmailAddress(username)
            .orElseThrow(() -> new WebAuthnSampleEntityNotFoundException(ResultMessages.error().add(MessageCodes.Error.User.USER_NOT_FOUND)));
    AuthenticatorEntity authenticatorEntity = modelMapper.map(authenticator, AuthenticatorEntity.class);
    authenticatorEntity.setUser(userEntity);
    userEntity.getAuthenticators().add(authenticatorEntity);
}
 
Example #22
Source File: UserManagerImpl.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@Override
public void removeAuthenticator(String username, Authenticator authenticator) {
    UserEntity userEntity = userEntityRepository.findOneByEmailAddress(username)
            .orElseThrow(() -> new WebAuthnSampleEntityNotFoundException(ResultMessages.error().add(MessageCodes.Error.User.USER_NOT_FOUND)));
    boolean found = userEntity.getAuthenticators().remove(authenticator);
    if (!found) {
        throw new WebAuthnSampleEntityNotFoundException(ResultMessages.error().add(MessageCodes.Error.Authenticator.AUTHENTICATOR_NOT_FOUND));
    }
}
 
Example #23
Source File: UserManagerImpl.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@Override
public void removeAuthenticator(String username, byte[] credentialId) {
    UserEntity userEntity = userEntityRepository.findOneByEmailAddress(username)
            .orElseThrow(() -> new WebAuthnSampleEntityNotFoundException(ResultMessages.error().add(MessageCodes.Error.User.USER_NOT_FOUND)));
    boolean found = userEntity.getAuthenticators().removeIf(item -> Arrays.equals(item.getAttestedCredentialData().getCredentialId(), credentialId));
    if (!found) {
        throw new WebAuthnSampleEntityNotFoundException(ResultMessages.error().add(MessageCodes.Error.Authenticator.AUTHENTICATOR_NOT_FOUND));
    }
}
 
Example #24
Source File: UserManagerImpl.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@Override
public void addAuthenticator(String username, Authenticator authenticator) {
    UserEntity userEntity = userEntityRepository.findOneByEmailAddress(username)
            .orElseThrow(() -> new WebAuthnSampleEntityNotFoundException(ResultMessages.error().add(MessageCodes.Error.User.USER_NOT_FOUND)));
    AuthenticatorEntity authenticatorEntity = modelMapper.map(authenticator, AuthenticatorEntity.class);
    authenticatorEntity.setUser(userEntity);
    userEntity.getAuthenticators().add(authenticatorEntity);
}
 
Example #25
Source File: UserManagerImpl.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@Override
public void removeAuthenticator(String username, Authenticator authenticator) {
    UserEntity userEntity = userEntityRepository.findOneByEmailAddress(username)
            .orElseThrow(() -> new WebAuthnSampleEntityNotFoundException(ResultMessages.error().add(MessageCodes.Error.User.USER_NOT_FOUND)));
    boolean found = userEntity.getAuthenticators().remove(authenticator);
    if (!found) {
        throw new WebAuthnSampleEntityNotFoundException(ResultMessages.error().add(MessageCodes.Error.Authenticator.AUTHENTICATOR_NOT_FOUND));
    }
}
 
Example #26
Source File: UserManagerImpl.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@Override
public void removeAuthenticator(String username, byte[] credentialId) {
    UserEntity userEntity = userEntityRepository.findOneByEmailAddress(username)
            .orElseThrow(() -> new WebAuthnSampleEntityNotFoundException(ResultMessages.error().add(MessageCodes.Error.User.USER_NOT_FOUND)));
    boolean found = userEntity.getAuthenticators().removeIf(item -> Arrays.equals(item.getAttestedCredentialData().getCredentialId(), credentialId));
    if (!found) {
        throw new WebAuthnSampleEntityNotFoundException(ResultMessages.error().add(MessageCodes.Error.Authenticator.AUTHENTICATOR_NOT_FOUND));
    }
}
 
Example #27
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 #28
Source File: AuthenticationObjectTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void equals_hashCode_test() {

    byte[] credentialId = new byte[32];
    CollectedClientData clientData = TestDataUtil.createClientData(ClientDataType.CREATE);
    byte[] clientDataBytes = new CollectedClientDataConverter(objectConverter).convertToBytes(clientData);
    AuthenticatorData<AuthenticationExtensionAuthenticatorOutput<?>> authenticatorData = TestDataUtil.createAuthenticatorData();
    byte[] authenticatorDataBytes = new AuthenticatorDataConverter(objectConverter).convert(authenticatorData);
    AuthenticationExtensionsClientOutputs<AuthenticationExtensionClientOutput<?>> clientExtensions = new AuthenticationExtensionsClientOutputs<>();
    ServerProperty serverProperty = TestDataUtil.createServerProperty();
    Authenticator authenticator = TestDataUtil.createAuthenticator();

    AuthenticationObject instanceA = new AuthenticationObject(
            credentialId,
            authenticatorData,
            authenticatorDataBytes,
            clientData,
            clientDataBytes,
            clientExtensions,
            serverProperty,
            authenticator
    );

    AuthenticationObject instanceB = new AuthenticationObject(
            credentialId,
            authenticatorData,
            authenticatorDataBytes,
            clientData,
            clientDataBytes,
            clientExtensions,
            serverProperty,
            authenticator
    );

    assertAll(
            () -> assertThat(instanceA).isEqualTo(instanceB),
            () -> assertThat(instanceA).hasSameHashCodeAs(instanceB)
    );
}
 
Example #29
Source File: FIDOU2FAuthenticatorAuthenticationValidationTest.java    From webauthn4j with Apache License 2.0 4 votes vote down vote up
@Test
void validate_assertion_with_UP_flag_off_test() {
    FIDOU2FAuthenticatorAdaptor fidou2FAuthenticatorAdaptor = new FIDOU2FAuthenticatorAdaptor();
    fidou2FAuthenticatorAdaptor.getFIDOU2FAuthenticator().setFlags(FIDOU2FAuthenticator.FLAG_OFF);
    clientPlatform = new ClientPlatform(origin, fidou2FAuthenticatorAdaptor);
    String rpId = "example.com";
    long timeout = 0;
    Challenge challenge = new DefaultChallenge();

    // create
    AttestationObject attestationObject = createAttestationObject(rpId, challenge);

    // get
    PublicKeyCredentialRequestOptions credentialRequestOptions = new PublicKeyCredentialRequestOptions(
            challenge,
            timeout,
            rpId,
            Collections.singletonList(
                    new PublicKeyCredentialDescriptor(
                            PublicKeyCredentialType.PUBLIC_KEY,
                            attestationObject.getAuthenticatorData().getAttestedCredentialData().getCredentialId(),
                            CollectionUtil.unmodifiableSet(AuthenticatorTransport.USB, AuthenticatorTransport.NFC, AuthenticatorTransport.BLE)
                    )
            ),
            UserVerificationRequirement.DISCOURAGED,
            null
    );
    PublicKeyCredential<AuthenticatorAssertionResponse, AuthenticationExtensionClientOutput<?>> credential = clientPlatform.get(credentialRequestOptions);
    AuthenticatorAssertionResponse authenticatorAssertionResponse = credential.getAuthenticatorResponse();

    ServerProperty serverProperty = new ServerProperty(origin, rpId, challenge, null);
    Authenticator authenticator = TestDataUtil.createAuthenticator(attestationObject);

    AuthenticationRequest authenticationRequest =
            new AuthenticationRequest(
                    credential.getRawId(),
                    authenticatorAssertionResponse.getAuthenticatorData(),
                    authenticatorAssertionResponse.getClientDataJSON(),
                    authenticatorAssertionResponse.getSignature()
            );
    AuthenticationParameters authenticationParameters =
            new AuthenticationParameters(
                    serverProperty,
                    authenticator,
                    false,
                    true
            );
    assertThrows(UserNotPresentException.class,
            () -> target.validate(authenticationRequest, authenticationParameters)
    );
}
 
Example #30
Source File: FIDOU2FAuthenticatorAuthenticationValidationTest.java    From webauthn4j with Apache License 2.0 4 votes vote down vote up
@Test
void validate_test() {
    String rpId = "example.com";
    long timeout = 0;
    Challenge challenge = new DefaultChallenge();

    // create
    AttestationObject attestationObject = createAttestationObject(rpId, challenge);

    // get
    PublicKeyCredentialRequestOptions credentialRequestOptions = new PublicKeyCredentialRequestOptions(
            challenge,
            timeout,
            rpId,
            Collections.singletonList(
                    new PublicKeyCredentialDescriptor(
                            PublicKeyCredentialType.PUBLIC_KEY,
                            attestationObject.getAuthenticatorData().getAttestedCredentialData().getCredentialId(),
                            CollectionUtil.unmodifiableSet(AuthenticatorTransport.USB, AuthenticatorTransport.NFC, AuthenticatorTransport.BLE)
                    )
            ),
            UserVerificationRequirement.DISCOURAGED,
            null
    );
    PublicKeyCredential<AuthenticatorAssertionResponse, AuthenticationExtensionClientOutput<?>> credential = clientPlatform.get(credentialRequestOptions);
    AuthenticatorAssertionResponse authenticationRequest = credential.getAuthenticatorResponse();
    AuthenticationExtensionsClientOutputs<AuthenticationExtensionClientOutput<?>> clientExtensionResults = credential.getClientExtensionResults();
    String clientExtensionJSON = authenticationExtensionsClientOutputsConverter.convertToString(clientExtensionResults);

    ServerProperty serverProperty = new ServerProperty(origin, rpId, challenge, null);
    Authenticator authenticator = TestDataUtil.createAuthenticator(attestationObject);

    AuthenticationRequest webAuthnAuthenticationRequest =
            new AuthenticationRequest(
                    credential.getRawId(),
                    authenticationRequest.getAuthenticatorData(),
                    authenticationRequest.getClientDataJSON(),
                    clientExtensionJSON,
                    authenticationRequest.getSignature()
            );
    AuthenticationParameters webAuthnAuthenticationParameters =
            new AuthenticationParameters(
                    serverProperty,
                    authenticator,
                    false,
                    true,
                    Collections.emptyList()
            );

    AuthenticationData response = target.validate(webAuthnAuthenticationRequest, webAuthnAuthenticationParameters);

    assertAll(
            () -> assertThat(response.getCollectedClientData()).isNotNull(),
            () -> assertThat(response.getAuthenticatorData()).isNotNull(),
            () -> assertThat(response.getClientExtensions()).isNotNull()
    );
}