Search in sources :

Example 1 with WebAuthnAuthenticator

use of com.webauthn4j.springframework.security.authenticator.WebAuthnAuthenticator in project webauthn4j-spring-security by webauthn4j.

the class WebAuthnAuthenticationProviderTest method authenticate_test.

/**
 * 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");
    UserDetails webAuthnPrincipal = new TestUserDetailsImpl("dummy", Collections.singletonList(grantedAuthority));
    WebAuthnAuthenticator webAuthnAuthenticator = mock(WebAuthnAuthenticator.class, RETURNS_DEEP_STUBS);
    when(webAuthnAuthenticator.getUserPrincipal()).thenReturn(webAuthnPrincipal);
    when(webAuthnAuthenticator.getAttestedCredentialData().getCredentialId()).thenReturn(credentialId);
    // When
    WebAuthnAuthenticationRequest request = mock(WebAuthnAuthenticationRequest.class);
    WebAuthnAuthenticationParameters parameters = mock(WebAuthnAuthenticationParameters.class);
    when(request.getCredentialId()).thenReturn(credentialId);
    when(authenticatorService.loadAuthenticatorByCredentialId(credentialId)).thenReturn(webAuthnAuthenticator);
    when(parameters.getServerProperty()).thenReturn(mock(ServerProperty.class));
    Authentication token = new WebAuthnAssertionAuthenticationToken(request, parameters, null);
    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());
    assertThat(authenticatedToken.getPrincipal()).isEqualTo(webAuthnPrincipal);
    assertThat(authenticatedToken.getCredentials()).isEqualTo(request);
    assertThat(authenticatedToken.getAuthorities().toArray()).containsExactly(grantedAuthority);
}
Also used : TestUserDetailsImpl(test.TestUserDetailsImpl) AuthenticationParameters(com.webauthn4j.data.AuthenticationParameters) ServerProperty(com.webauthn4j.server.ServerProperty) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) WebAuthnAuthenticator(com.webauthn4j.springframework.security.authenticator.WebAuthnAuthenticator) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) UserDetails(org.springframework.security.core.userdetails.UserDetails) Authentication(org.springframework.security.core.Authentication) AuthenticationRequest(com.webauthn4j.data.AuthenticationRequest) Test(org.junit.Test)

Example 2 with WebAuthnAuthenticator

use of com.webauthn4j.springframework.security.authenticator.WebAuthnAuthenticator in project webauthn4j-spring-security by webauthn4j.

the class WebAuthnAuthenticationProviderTest method authenticate_with_BadChallengeException_from_authenticationContextValidator_test.

/**
 * 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];
    WebAuthnAuthenticatorImpl authenticator = mock(WebAuthnAuthenticatorImpl.class, RETURNS_DEEP_STUBS);
    WebAuthnAuthenticator webAuthnAuthenticator = mock(WebAuthnAuthenticator.class);
    when(authenticator.getAttestedCredentialData().getCredentialId()).thenReturn(credentialId);
    when(webAuthnAuthenticator.getAttestedCredentialData()).thenReturn(mock(AttestedCredentialData.class));
    when(webAuthnAuthenticator.getAttestationStatement()).thenReturn(mock(AttestationStatement.class));
    doThrow(com.webauthn4j.validator.exception.BadChallengeException.class).when(webAuthnManager).validate((AuthenticationRequest) any(), any());
    // When
    WebAuthnAuthenticationRequest request = mock(WebAuthnAuthenticationRequest.class);
    WebAuthnAuthenticationParameters parameters = mock(WebAuthnAuthenticationParameters.class);
    when(request.getCredentialId()).thenReturn(credentialId);
    when(authenticatorService.loadAuthenticatorByCredentialId(credentialId)).thenReturn(webAuthnAuthenticator);
    when(parameters.getServerProperty()).thenReturn(mock(ServerProperty.class));
    Authentication token = new WebAuthnAssertionAuthenticationToken(request, parameters, null);
    authenticationProvider.authenticate(token);
}
Also used : WebAuthnAuthenticator(com.webauthn4j.springframework.security.authenticator.WebAuthnAuthenticator) AttestedCredentialData(com.webauthn4j.data.attestation.authenticator.AttestedCredentialData) ServerProperty(com.webauthn4j.server.ServerProperty) WebAuthnAuthenticatorImpl(com.webauthn4j.springframework.security.authenticator.WebAuthnAuthenticatorImpl) Authentication(org.springframework.security.core.Authentication) AttestationStatement(com.webauthn4j.data.attestation.statement.AttestationStatement) Test(org.junit.Test)

Example 3 with WebAuthnAuthenticator

use of com.webauthn4j.springframework.security.authenticator.WebAuthnAuthenticator in project webauthn4j-spring-security by webauthn4j.

the class WebAuthnAuthenticationProviderTest method retrieveAuthenticator_test.

@Test
public void retrieveAuthenticator_test() {
    byte[] credentialId = new byte[0];
    WebAuthnAuthenticator expectedAuthenticator = mock(WebAuthnAuthenticator.class);
    // Given
    when(authenticatorService.loadAuthenticatorByCredentialId(credentialId)).thenReturn(expectedAuthenticator);
    // When
    WebAuthnAuthenticator webAuthnAuthenticator = authenticationProvider.retrieveAuthenticator(credentialId);
    // Then
    assertThat(webAuthnAuthenticator).isEqualTo(expectedAuthenticator);
}
Also used : WebAuthnAuthenticator(com.webauthn4j.springframework.security.authenticator.WebAuthnAuthenticator) Test(org.junit.Test)

Example 4 with WebAuthnAuthenticator

use of com.webauthn4j.springframework.security.authenticator.WebAuthnAuthenticator in project webauthn4j-spring-security by webauthn4j.

the class AssertionOptionsProviderImplTest method getAssertionOptions_test.

@Test
public void getAssertionOptions_test() {
    Challenge challenge = new DefaultChallenge();
    byte[] credentialId = new byte[] { 0x01, 0x23, 0x45 };
    Set<AuthenticatorTransport> transports = Collections.singleton(AuthenticatorTransport.INTERNAL);
    RpIdProvider rpIdProvider = new RpIdProviderImpl();
    WebAuthnAuthenticatorService authenticatorService = mock(WebAuthnAuthenticatorService.class);
    WebAuthnAuthenticator authenticator = mock(WebAuthnAuthenticator.class, RETURNS_DEEP_STUBS);
    when(authenticator.getTransports()).thenReturn(transports);
    List<WebAuthnAuthenticator> authenticators = Collections.singletonList(authenticator);
    ChallengeRepository challengeRepository = mock(ChallengeRepository.class);
    MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    when(authenticatorService.loadAuthenticatorsByUserPrincipal(any())).thenReturn(authenticators);
    when(authenticator.getAttestedCredentialData().getCredentialId()).thenReturn(credentialId);
    when(challengeRepository.loadOrGenerateChallenge(mockRequest)).thenReturn(challenge);
    AssertionOptionsProviderImpl assertionOptionsProvider = new AssertionOptionsProviderImpl(rpIdProvider, authenticatorService, challengeRepository);
    assertionOptionsProvider.setRpId("example.com");
    assertionOptionsProvider.setAuthenticationTimeout(10000L);
    assertionOptionsProvider.setAuthenticationUserVerification(UserVerificationRequirement.REQUIRED);
    assertionOptionsProvider.setAuthenticationExtensions(new AuthenticationExtensionsClientInputs<>());
    AssertionOptions assertionOptions = assertionOptionsProvider.getAssertionOptions(mockRequest, new UsernamePasswordAuthenticationToken("username", null));
    assertThat(assertionOptions.getChallenge()).isEqualTo(challenge);
    assertThat(assertionOptions.getTimeout()).isEqualTo(10000L);
    assertThat(assertionOptions.getRpId()).isEqualTo("example.com");
    assertThat(assertionOptions.getAllowCredentials()).containsExactly(new PublicKeyCredentialDescriptor(PublicKeyCredentialType.PUBLIC_KEY, credentialId, transports));
    assertThat(assertionOptions.getUserVerification()).isEqualTo(UserVerificationRequirement.REQUIRED);
    assertThat(assertionOptions.getExtensions()).isEqualTo(new AuthenticationExtensionsClientInputs<>());
}
Also used : ChallengeRepository(com.webauthn4j.springframework.security.challenge.ChallengeRepository) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) Challenge(com.webauthn4j.data.client.challenge.Challenge) DefaultChallenge(com.webauthn4j.data.client.challenge.DefaultChallenge) WebAuthnAuthenticator(com.webauthn4j.springframework.security.authenticator.WebAuthnAuthenticator) DefaultChallenge(com.webauthn4j.data.client.challenge.DefaultChallenge) WebAuthnAuthenticatorService(com.webauthn4j.springframework.security.authenticator.WebAuthnAuthenticatorService) Test(org.junit.Test)

Example 5 with WebAuthnAuthenticator

use of com.webauthn4j.springframework.security.authenticator.WebAuthnAuthenticator in project webauthn4j-spring-security by webauthn4j.

the class WebAuthnSampleController method create.

@PostMapping(value = "/signup")
public String create(HttpServletRequest request, @Valid @ModelAttribute("userForm") UserCreateForm userCreateForm, BindingResult result, Model model, RedirectAttributes redirectAttributes) {
    try {
        if (result.hasErrors()) {
            model.addAttribute("errorMessage", "Your input needs correction.");
            logger.debug("User input validation failed.");
            return VIEW_SIGNUP_SIGNUP;
        }
        WebAuthnRegistrationRequestValidationResponse registrationRequestValidationResponse;
        try {
            registrationRequestValidationResponse = registrationRequestValidator.validate(request, userCreateForm.getAuthenticator().getClientDataJSON(), userCreateForm.getAuthenticator().getAttestationObject(), userCreateForm.getAuthenticator().getTransports(), userCreateForm.getAuthenticator().getClientExtensions());
        } catch (WebAuthnException | WebAuthnAuthenticationException e) {
            model.addAttribute("errorMessage", "Authenticator registration request validation failed. Please try again.");
            logger.debug("WebAuthn registration request validation failed.", e);
            return VIEW_SIGNUP_SIGNUP;
        }
        String username = userCreateForm.getUsername();
        String password = passwordEncoder.encode(userCreateForm.getPassword());
        boolean singleFactorAuthenticationAllowed = userCreateForm.isSingleFactorAuthenticationAllowed();
        List<GrantedAuthority> authorities;
        if (singleFactorAuthenticationAllowed) {
            authorities = Collections.singletonList(new SimpleGrantedAuthority("SINGLE_FACTOR_AUTHN_ALLOWED"));
        } else {
            authorities = Collections.emptyList();
        }
        User user = new User(username, password, authorities);
        WebAuthnAuthenticator authenticator = new WebAuthnAuthenticatorImpl("authenticator", user.getUsername(), registrationRequestValidationResponse.getAttestationObject().getAuthenticatorData().getAttestedCredentialData(), registrationRequestValidationResponse.getAttestationObject().getAttestationStatement(), registrationRequestValidationResponse.getAttestationObject().getAuthenticatorData().getSignCount(), registrationRequestValidationResponse.getTransports(), registrationRequestValidationResponse.getRegistrationExtensionsClientOutputs(), registrationRequestValidationResponse.getAttestationObject().getAuthenticatorData().getExtensions());
        try {
            userDetailsManager.createUser(user);
            webAuthnAuthenticatorManager.createAuthenticator(authenticator);
        } catch (IllegalArgumentException ex) {
            model.addAttribute("errorMessage", "Registration failed. The user may already be registered.");
            logger.debug("Registration failed.", ex);
            return VIEW_SIGNUP_SIGNUP;
        }
    } catch (RuntimeException ex) {
        model.addAttribute("errorMessage", "Registration failed by unexpected error.");
        logger.debug("Registration failed.", ex);
        return VIEW_SIGNUP_SIGNUP;
    }
    redirectAttributes.addFlashAttribute("successMessage", "User registration finished.");
    return REDIRECT_LOGIN;
}
Also used : WebAuthnAuthenticationException(com.webauthn4j.springframework.security.exception.WebAuthnAuthenticationException) User(org.springframework.security.core.userdetails.User) WebAuthnAuthenticatorImpl(com.webauthn4j.springframework.security.authenticator.WebAuthnAuthenticatorImpl) WebAuthnRegistrationRequestValidationResponse(com.webauthn4j.springframework.security.WebAuthnRegistrationRequestValidationResponse) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) WebAuthnAuthenticator(com.webauthn4j.springframework.security.authenticator.WebAuthnAuthenticator) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) WebAuthnException(com.webauthn4j.util.exception.WebAuthnException) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Aggregations

WebAuthnAuthenticator (com.webauthn4j.springframework.security.authenticator.WebAuthnAuthenticator)8 Test (org.junit.Test)5 Challenge (com.webauthn4j.data.client.challenge.Challenge)3 WebAuthnAuthenticatorImpl (com.webauthn4j.springframework.security.authenticator.WebAuthnAuthenticatorImpl)3 ChallengeRepository (com.webauthn4j.springframework.security.challenge.ChallengeRepository)3 Authentication (org.springframework.security.core.Authentication)3 GrantedAuthority (org.springframework.security.core.GrantedAuthority)3 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)3 DefaultChallenge (com.webauthn4j.data.client.challenge.DefaultChallenge)2 ServerProperty (com.webauthn4j.server.ServerProperty)2 WebAuthnRegistrationRequestValidationResponse (com.webauthn4j.springframework.security.WebAuthnRegistrationRequestValidationResponse)2 WebAuthnAuthenticatorService (com.webauthn4j.springframework.security.authenticator.WebAuthnAuthenticatorService)2 WebAuthnAuthenticationException (com.webauthn4j.springframework.security.exception.WebAuthnAuthenticationException)2 WebAuthnException (com.webauthn4j.util.exception.WebAuthnException)2 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)2 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)2 User (org.springframework.security.core.userdetails.User)2 AuthenticationParameters (com.webauthn4j.data.AuthenticationParameters)1 AuthenticationRequest (com.webauthn4j.data.AuthenticationRequest)1 AttestedCredentialData (com.webauthn4j.data.attestation.authenticator.AttestedCredentialData)1