/** * Handles the creation of the final <tt>Authentication</tt> object which will be * returned by the provider. * <p> * The default implementation just creates a new OpenIDAuthenticationToken from the * original, but with the UserDetails as the principal and including the authorities * loaded by the UserDetailsService. * * @param userDetails the loaded UserDetails object * @param auth the token passed to the authenticate method, containing * @return the token which will represent the authenticated user. */ protected Authentication createSuccessfulAuthentication(UserDetails userDetails, OpenIDAuthenticationToken auth) { return new OpenIDAuthenticationToken(userDetails, this.authoritiesMapper.mapAuthorities(userDetails.getAuthorities()), auth.getIdentityUrl(), auth.getAttributes()); }
@Test public void testAuthenticateSuccess() { OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); provider.setUserDetailsService(new MockUserDetailsService()); Authentication preAuth = new OpenIDAuthenticationToken( OpenIDAuthenticationStatus.SUCCESS, USERNAME, "", null); assertThat(preAuth.isAuthenticated()).isFalse(); Authentication postAuth = provider.authenticate(preAuth); assertThat(postAuth).isNotNull(); assertThat(postAuth instanceof OpenIDAuthenticationToken).isTrue(); assertThat(postAuth.isAuthenticated()).isTrue(); assertThat(postAuth.getPrincipal()).isNotNull(); assertThat(postAuth.getPrincipal() instanceof UserDetails).isTrue(); assertThat(postAuth.getAuthorities()).isNotNull(); assertThat(postAuth.getAuthorities().size() > 0).isTrue(); assertThat( ((OpenIDAuthenticationToken) postAuth).getStatus() == OpenIDAuthenticationStatus.SUCCESS).isTrue(); assertThat(((OpenIDAuthenticationToken) postAuth).getMessage() == null).isTrue(); }
/** * Created by the <tt>OpenIDAuthenticationProvider</tt> on successful authentication. * * @param principal usually the <tt>UserDetails</tt> returned by the configured * <tt>UserDetailsService</tt> used by the <tt>OpenIDAuthenticationProvider</tt>. * */ public OpenIDAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities, String identityUrl, List<OpenIDAttribute> attributes) { super(authorities); this.principal = principal; this.status = OpenIDAuthenticationStatus.SUCCESS; this.identityUrl = identityUrl; this.message = null; this.attributes = attributes; setAuthenticated(true); }
OpenIDAuthenticationStatus status = response.getStatus(); "Error message from server: " + response.getMessage());
public Builder withAuthenticationToken(OpenIDAuthenticationToken token) { this.username = token.getIdentityUrl(); for (OpenIDAttribute attribute : token.getAttributes()) { if (attribute.getName().equals("email")) { this.email = attribute.getValues().get(0); } if (attribute.getName().equals("firstname")) { this.firstname = attribute.getValues().get(0); } if (attribute.getName().equals("lastname")) { this.lastname = attribute.getValues().get(0); } if (attribute.getName().equals("fullname")) { this.fullname = attribute.getValues().get(0); } } return this; }
if (token.getStatus() == OpenIDAuthenticationStatus.SUCCESS) { String openId = token.getIdentityUrl(); if (securityRealm.getUserForOpenId(openId) != null) { validationContext.addError("The OpenID supplied is already mapped to a user."); validationContext.addError(StringUtils.transformHTML(token.getMessage()));
private AbstractAuthenticationToken getToken(Authentication authentication, MotechUser user) { AbstractAuthenticationToken token = null; if (authentication instanceof UsernamePasswordAuthenticationToken) { UsernamePasswordAuthenticationToken oldToken = (UsernamePasswordAuthenticationToken) authentication; token = new UsernamePasswordAuthenticationToken(oldToken.getPrincipal(), oldToken.getCredentials(), authoritiesService.authoritiesFor(user)); } else if (authentication instanceof OpenIDAuthenticationToken) { OpenIDAuthenticationToken oldToken = (OpenIDAuthenticationToken) authentication; token = new OpenIDAuthenticationToken(oldToken.getPrincipal(), authoritiesService.authoritiesFor(user), user.getOpenId(), oldToken.getAttributes()); } return token; }
@Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { if(exception instanceof UsernameNotFoundException && exception.getAuthentication() instanceof OpenIDAuthenticationToken && ((OpenIDAuthenticationToken)exception.getAuthentication()).getStatus().equals(OpenIDAuthenticationStatus.SUCCESS)) { OpenIDAuthenticationToken token = (OpenIDAuthenticationToken)exception.getAuthentication(); String url = token.getIdentityUrl(); User user = createTemporaryUser(token, url); request.getSession(true).setAttribute(ModelKeys.NEW_USER, user); DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); log.info("Redirecting to new user account creation page"); super.setRedirectStrategy(redirectStrategy); redirectStrategy.sendRedirect(request, response, "/"+ViewNames.CREATE_ACCOUNT_PAGE); return; } else { super.onAuthenticationFailure(request, response, exception); } }
String fullName = null; List<OpenIDAttribute> attributes = token.getAttributes();
@Override public UserDetails loadUserDetails(OpenIDAuthenticationToken token) throws UsernameNotFoundException { final String openId = token.getIdentityUrl(); User user = this.getUserByOpenId(openId); if (user == null) { log.info("Open ID User with URL "+openId+" was not found!"); throw new UsernameNotFoundException("Open ID User with URL "+openId+" was not found!"); } return user; } }
return new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.FAILURE, id == null ? "Unknown" : id.getIdentifier(), "Verification status message: [" + verification.getStatusMsg() + "]", verification.getAuthResponse(), attributesToFetch); return new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.SUCCESS, verified.getIdentifier(), "some message", attributes);
@Override public UserDetails loadUserDetails(OpenIDAuthenticationToken token) { MotechUser user = allMotechUsers.findUserByOpenId(token.getName()); if (user == null) { List<String> roles = new ArrayList<String>(); if (allMotechUsers.getOpenIdUsers().isEmpty()) { for (MotechRole role : allMotechRoles.getRoles()) { roles.add(role.getRoleName()); } } user = new MotechUser(getAttribute(token.getAttributes(), "Email"), "", getAttribute(token.getAttributes(), "Email"), "", roles, token.getName(), Locale.getDefault()); allMotechUsers.addOpenIdUser(user); } return new User(user.getUserName(), user.getPassword(), user.isActive(), true, true, true, authoritiesService.authoritiesFor(user)); }
@Test public void failedVerificationReturnsFailedAuthenticationStatus() throws Exception { ConsumerManager mgr = mock(ConsumerManager.class); OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); VerificationResult vr = mock(VerificationResult.class); DiscoveryInformation di = mock(DiscoveryInformation.class); when( mgr.verify(any(), any(ParameterList.class), any(DiscoveryInformation.class))).thenReturn(vr); MockHttpServletRequest request = new MockHttpServletRequest(); request.getSession().setAttribute(DiscoveryInformation.class.getName(), di); OpenIDAuthenticationToken auth = consumer.endConsumption(request); assertThat(auth.getStatus()).isEqualTo(OpenIDAuthenticationStatus.FAILURE); }
token.setDetails(authenticationDetailsSource.buildDetails(request));
OpenIDAuthenticationToken newAuthentication = new OpenIDAuthenticationToken(userDetails, userDetails.getAuthorities(), openidAuthenticationToken.getIdentityUrl(), openidAuthenticationToken.getAttributes());
OpenIDAuthenticationStatus status = response.getStatus(); "Error message from server: " + response.getMessage());
private User createTemporaryUser(OpenIDAuthenticationToken token, final String openId) { final List<OpenIDAttribute> attributes = token.getAttributes(); String email = null; String firstName = null;
@Override public UserDetails loadUserDetails(OpenIDAuthenticationToken token) throws UsernameNotFoundException { String identity = token.getIdentityUrl(); UserIdentifier identifier = new UserIdentifier(identity); User user = userRepository.findByIdentifier(identifier); if (user != null) { // TODO: update account } else { // TODO: add user } Builder builder = new Builder().withAuthenticationToken(token); if (user != null) { for (RoleIdentifier role : user.getRoles()) { builder.addGrantedAuthority(new SimpleGrantedAuthority(role.getIdentifier())); } } return builder.build(); }
@Test public void testAuthenticateError() { OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); provider.setUserDetailsService(new MockUserDetailsService()); Authentication preAuth = new OpenIDAuthenticationToken( OpenIDAuthenticationStatus.ERROR, USERNAME, "", null); assertThat(preAuth.isAuthenticated()).isFalse(); try { provider.authenticate(preAuth); fail("Should throw an AuthenticationException"); } catch (AuthenticationServiceException expected) { assertThat(expected.getMessage()).isEqualTo("Error message from server: "); } }
@SuppressWarnings("serial") @Test public void successfulVerificationReturnsExpectedAuthentication() throws Exception { ConsumerManager mgr = mock(ConsumerManager.class); OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); VerificationResult vr = mock(VerificationResult.class); DiscoveryInformation di = mock(DiscoveryInformation.class); Identifier id = new Identifier() { public String getIdentifier() { return "id"; } }; Message msg = mock(Message.class); when( mgr.verify(any(), any(ParameterList.class), any(DiscoveryInformation.class))).thenReturn(vr); when(vr.getVerifiedId()).thenReturn(id); when(vr.getAuthResponse()).thenReturn(msg); MockHttpServletRequest request = new MockHttpServletRequest(); request.getSession().setAttribute(DiscoveryInformation.class.getName(), di); request.getSession().setAttribute( "SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST", attributes); OpenIDAuthenticationToken auth = consumer.endConsumption(request); assertThat(auth.getStatus()).isEqualTo(OpenIDAuthenticationStatus.SUCCESS); }