com.webauthn4j.data.AuthenticationRequest Java Examples

The following examples show how to use com.webauthn4j.data.AuthenticationRequest. 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
/**
 * Verifies that validation fails if ValidationException is thrown from authenticationContextValidator
 */
@Test(expected = BadChallengeException.class)
public void authenticate_with_BadChallengeException_from_authenticationContextValidator_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);

    doThrow(com.webauthn4j.validator.exception.BadChallengeException.class).when(webAuthnManager).validate((AuthenticationRequest) any(), any());

    //When
    WebAuthnAuthenticationRequest credential = mock(WebAuthnAuthenticationRequest.class);
    when(credential.getCredentialId()).thenReturn(credentialId);
    when(userDetailsService.loadUserByCredentialId(credentialId)).thenReturn(user);
    Authentication token = new WebAuthnAssertionAuthenticationToken(credential);
    authenticationProvider.authenticate(token);
}
 
Example #2
Source File: WebAuthnAuthenticationManager.java    From webauthn4j with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("squid:S1130")
public AuthenticationData parse(AuthenticationRequest authenticationRequest) throws DataConversionException {

    byte[] credentialId = authenticationRequest.getCredentialId();
    byte[] signature = authenticationRequest.getSignature();
    byte[] userHandle = authenticationRequest.getUserHandle();
    byte[] clientDataBytes = authenticationRequest.getClientDataJSON();
    CollectedClientData collectedClientData = collectedClientDataConverter.convert(clientDataBytes);
    byte[] authenticatorDataBytes = authenticationRequest.getAuthenticatorData();
    AuthenticatorData<AuthenticationExtensionAuthenticatorOutput<?>> authenticatorData = authenticatorDataConverter.convert(authenticatorDataBytes);

    AuthenticationExtensionsClientOutputs<AuthenticationExtensionClientOutput<?>> clientExtensions =
            authenticationExtensionsClientOutputsConverter.convert(authenticationRequest.getClientExtensionsJSON());

    return new AuthenticationData(
            credentialId,
            userHandle,
            authenticatorData,
            authenticatorDataBytes,
            collectedClientData,
            clientDataBytes,
            clientExtensions,
            signature
    );

}
 
Example #3
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 #4
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 #5
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 #6
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 #7
Source File: WebAuthnCredentialModelInput.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public AuthenticationRequest getAuthenticationRequest() {
    return authenticationRequest;
}
 
Example #8
Source File: WebAuthnCredentialModelInput.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public void setAuthenticationRequest(AuthenticationRequest authenticationRequest) {
    this.authenticationRequest = authenticationRequest;
}