com.webauthn4j.data.AuthenticationParameters Java Examples

The following examples show how to use com.webauthn4j.data.AuthenticationParameters. 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: 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 #2
Source File: WebAuthnAuthenticationProviderTest.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that authentication process passes successfully if input is correct.
 */
@Test
public void authenticate_test() {
    //Given
    byte[] credentialId = new byte[32];
    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_ADMIN");
    WebAuthnAuthenticator authenticator = mock(WebAuthnAuthenticator.class, RETURNS_DEEP_STUBS);
    WebAuthnUserDetailsImpl user = new WebAuthnUserDetailsImpl(
            new byte[0],
            "dummy",
            "dummy",
            Collections.singletonList(authenticator),
            Collections.singletonList(grantedAuthority));
    when(authenticator.getAttestedCredentialData().getCredentialId()).thenReturn(credentialId);

    //When
    WebAuthnAuthenticationRequest credential = mock(WebAuthnAuthenticationRequest.class);
    when(credential.getCredentialId()).thenReturn(credentialId);
    when(userDetailsService.loadUserByCredentialId(credentialId)).thenReturn(user);
    Authentication token = new WebAuthnAssertionAuthenticationToken(credential);
    Authentication authenticatedToken = authenticationProvider.authenticate(token);

    ArgumentCaptor<AuthenticationRequest> requestCaptor = ArgumentCaptor.forClass(AuthenticationRequest.class);
    ArgumentCaptor<AuthenticationParameters> parameterCaptor = ArgumentCaptor.forClass(AuthenticationParameters.class);
    verify(webAuthnManager).validate(requestCaptor.capture(), parameterCaptor.capture());
    AuthenticationParameters authenticationParameters = parameterCaptor.getValue();

    assertThat(authenticationParameters.getExpectedExtensionIds()).isEqualTo(credential.getExpectedAuthenticationExtensionIds());

    assertThat(authenticatedToken.getPrincipal()).isInstanceOf(WebAuthnUserDetailsImpl.class);
    assertThat(authenticatedToken.getCredentials()).isEqualTo(credential);
    assertThat(authenticatedToken.getAuthorities().toArray()).containsExactly(grantedAuthority);
}
 
Example #3
Source File: BeanAssertUtil.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
public static void validate(AuthenticationParameters authenticationParameters) {
    if (authenticationParameters == null) {
        throw new ConstraintViolationException("authenticationParameters must not be null");
    }
    if (authenticationParameters.getAuthenticator() == null) {
        throw new ConstraintViolationException("authenticator must not be null");
    }
    validate(authenticationParameters.getServerProperty());
}
 
Example #4
Source File: BeanAssertUtilTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void validate_AuthenticationParameters_test() {
    AuthenticationParameters authenticationParameters = new AuthenticationParameters(
            TestDataUtil.createServerProperty(),
            TestDataUtil.createAuthenticator(),
            true,
            true,
            new ArrayList<>()
    );
    BeanAssertUtil.validate(authenticationParameters);
}
 
Example #5
Source File: BeanAssertUtilTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void validate_AuthenticationParameters_with_serverProperty_null_test() {
    AuthenticationParameters authenticationParameters = new AuthenticationParameters(
            null,
            TestDataUtil.createAuthenticator(),
            true,
            true,
            new ArrayList<>()
    );
    assertThrows(ConstraintViolationException.class,
            () -> BeanAssertUtil.validate(authenticationParameters)
    );
}
 
Example #6
Source File: BeanAssertUtilTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void validate_AuthenticationParameters_with_authenticator_null_test() {
    AuthenticationParameters authenticationParameters = new AuthenticationParameters(
            TestDataUtil.createServerProperty(),
            null,
            true,
            true,
            new ArrayList<>()
    );
    assertThrows(ConstraintViolationException.class,
            () -> BeanAssertUtil.validate(authenticationParameters)
    );
}
 
Example #7
Source File: BeanAssertUtilTest.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
@Test
void validate_AuthenticationParameters_with_expectedExtensionIds_null_test() {
    AuthenticationParameters authenticationParameters = new AuthenticationParameters(
            TestDataUtil.createServerProperty(),
            TestDataUtil.createAuthenticator(),
            true,
            true,
            null
    );
    assertDoesNotThrow(
            () -> BeanAssertUtil.validate(authenticationParameters)
    );
}
 
Example #8
Source File: WebAuthnAuthenticationManager.java    From webauthn4j with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("squid:S1130")
public AuthenticationData validate(AuthenticationRequest authenticationRequest, AuthenticationParameters authenticationParameters) throws DataConversionException, ValidationException {
    AuthenticationData authenticationData = parse(authenticationRequest);
    validate(authenticationData, authenticationParameters);
    return authenticationData;
}
 
Example #9
Source File: WebAuthnAuthenticationManager.java    From webauthn4j with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("squid:S1130")
public AuthenticationData validate(AuthenticationData authenticationData, AuthenticationParameters authenticationParameters) throws ValidationException {
    authenticationDataValidator.validate(authenticationData, authenticationParameters);
    return authenticationData;
}
 
Example #10
Source File: BeanAssertUtilTest.java    From webauthn4j with Apache License 2.0 4 votes vote down vote up
@Test
void validate_AuthenticationParameters_with_null_test() {
    assertThrows(ConstraintViolationException.class,
            () -> BeanAssertUtil.validate((AuthenticationParameters) null)
    );
}
 
Example #11
Source File: WebAuthnAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public void action(AuthenticationFlowContext context) {
    MultivaluedMap<String, String> params = context.getHttpRequest().getDecodedFormParameters();

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

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

    String baseUrl = UriUtils.getOrigin(context.getUriInfo().getBaseUri());
    String rpId = getRpID(context);

    Origin origin = new Origin(baseUrl);
    Challenge challenge = new DefaultChallenge(context.getAuthenticationSession().getAuthNote(WebAuthnConstants.AUTH_CHALLENGE_NOTE));
    ServerProperty server = new ServerProperty(origin, rpId, challenge, null);

    byte[] credentialId = Base64Url.decode(params.getFirst(WebAuthnConstants.CREDENTIAL_ID));
    byte[] clientDataJSON = Base64Url.decode(params.getFirst(WebAuthnConstants.CLIENT_DATA_JSON));
    byte[] authenticatorData = Base64Url.decode(params.getFirst(WebAuthnConstants.AUTHENTICATOR_DATA));
    byte[] signature = Base64Url.decode(params.getFirst(WebAuthnConstants.SIGNATURE));

    final String userHandle = params.getFirst(WebAuthnConstants.USER_HANDLE);
    final String userId;
    // existing User Handle means that the authenticator used Resident Key supported public key credential
    if (userHandle == null || userHandle.isEmpty()) {
        // Resident Key not supported public key credential was used
        // so rely on the user that has already been authenticated
        userId = context.getUser().getId();
    } else {
        // decode using the same charset as it has been encoded (see: WebAuthnRegister.java)
        userId = new String(Base64Url.decode(userHandle), StandardCharsets.UTF_8);
        if (context.getUser() != null) {
            // Resident Key supported public key credential was used,
            // so need to confirm whether the already authenticated user is equals to one authenticated by the webauthn authenticator
            String firstAuthenticatedUserId = context.getUser().getId();
            if (firstAuthenticatedUserId != null && !firstAuthenticatedUserId.equals(userId)) {
                context.getEvent()
                        .detail("first_authenticated_user_id", firstAuthenticatedUserId)
                        .detail("web_authn_authenticator_authenticated_user_id", userId);
                setErrorResponse(context, WEBAUTHN_ERROR_DIFFERENT_USER, null);
                return;
            }
        } else {
            // Resident Key supported public key credential was used,
            // and the user has not yet been identified
            // so rely on the user authenticated by the webauthn authenticator
            // NOP
        }
    }

    boolean isUVFlagChecked = false;
    String userVerificationRequirement = getWebAuthnPolicy(context).getUserVerificationRequirement();
    if (WebAuthnConstants.OPTION_REQUIRED.equals(userVerificationRequirement)) isUVFlagChecked = true;

    UserModel user = session.users().getUserById(userId, context.getRealm());

    AuthenticationRequest authenticationRequest = new AuthenticationRequest(
            credentialId,
            authenticatorData,
            clientDataJSON,
            signature
            );

    AuthenticationParameters authenticationParameters = new AuthenticationParameters(
            server,
            null, // here authenticator cannot be fetched, set it afterwards in WebAuthnCredentialProvider.isValid()
            isUVFlagChecked
            );

    WebAuthnCredentialModelInput cred = new WebAuthnCredentialModelInput(getCredentialType());

    cred.setAuthenticationRequest(authenticationRequest);
    cred.setAuthenticationParameters(authenticationParameters);

    boolean result = false;
    try {
        result = session.userCredentialManager().isValid(context.getRealm(), user, cred);
    } catch (WebAuthnException wae) {
        setErrorResponse(context, WEBAUTHN_ERROR_AUTH_VERIFICATION, wae.getMessage());
        return;
    }
    String encodedCredentialID = Base64Url.encode(credentialId);
    if (result) {
        String isUVChecked = Boolean.toString(isUVFlagChecked);
        logger.debugv("WebAuthn Authentication successed. isUserVerificationChecked = {0}, PublicKeyCredentialID = {1}", isUVChecked, encodedCredentialID);
        context.setUser(user);
        context.getEvent()
            .detail("web_authn_authenticator_user_verification_checked", isUVChecked)
            .detail("public_key_credential_id", encodedCredentialID);
        context.success();
    } else {
        context.getEvent()
            .detail("web_authn_authenticated_user_id", userId)
            .detail("public_key_credential_id", encodedCredentialID);
        setErrorResponse(context, WEBAUTHN_ERROR_USER_NOT_FOUND, null);
        context.cancelLogin();
    }
}
 
Example #12
Source File: WebAuthnCredentialModelInput.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public AuthenticationParameters getAuthenticationParameters() {
    return authenticationParameters;
}
 
Example #13
Source File: WebAuthnCredentialModelInput.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public void setAuthenticationParameters(AuthenticationParameters authenticationParameters) {
    this.authenticationParameters = authenticationParameters;
}
 
Example #14
Source File: WebAuthnCredentialProvider.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) {
    if (!WebAuthnCredentialModelInput.class.isInstance(input)) return false;

    WebAuthnCredentialModelInput context = WebAuthnCredentialModelInput.class.cast(input);
    List<WebAuthnCredentialModelInput> auths = getWebAuthnCredentialModelList(realm, user);

    WebAuthnAuthenticationManager webAuthnAuthenticationManager = new WebAuthnAuthenticationManager();
    AuthenticationData authenticationData = null;

    try {
        for (WebAuthnCredentialModelInput auth : auths) {

            byte[] credentialId = auth.getAttestedCredentialData().getCredentialId();
            if (Arrays.equals(credentialId, context.getAuthenticationRequest().getCredentialId())) {
                Authenticator authenticator = new AuthenticatorImpl(
                        auth.getAttestedCredentialData(),
                        auth.getAttestationStatement(),
                        auth.getCount()
                );

                // parse
                authenticationData = webAuthnAuthenticationManager.parse(context.getAuthenticationRequest());
                // validate
                AuthenticationParameters authenticationParameters = new AuthenticationParameters(
                        context.getAuthenticationParameters().getServerProperty(),
                        authenticator,
                        context.getAuthenticationParameters().isUserVerificationRequired()
                );
                webAuthnAuthenticationManager.validate(authenticationData, authenticationParameters);


                logger.debugv("response.getAuthenticatorData().getFlags() = {0}", authenticationData.getAuthenticatorData().getFlags());

                // update authenticator counter
                long count = auth.getCount();
                CredentialModel credModel = getCredentialStore().getStoredCredentialById(realm, user, auth.getCredentialDBId());
                WebAuthnCredentialModel webAuthnCredModel = getCredentialFromModel(credModel);
                webAuthnCredModel.updateCounter(count + 1);
                getCredentialStore().updateCredential(realm, user, webAuthnCredModel);

                logger.debugf("Successfully validated WebAuthn credential for user %s", user.getUsername());
                dumpCredentialModel(webAuthnCredModel, auth);

                return true;
            }
        }
    } catch (WebAuthnException wae) {
        wae.printStackTrace();
        throw(wae);
    }
    // no authenticator matched
    return false;
}