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);
}
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);
}
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);
}
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<>());
}
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;
}
Aggregations