@Test
  public void testLoadUserByUsername() {
    UserDetails expectedUserDetails =
        new User(
            "EXISTING_USER",
            "PASSWORD",
            true,
            true,
            true,
            true,
            AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B"));
    UserDetails userDetails = userDetailsServiceWrapper.loadUserByUsername("EXISTING_USER");
    assertEquals(expectedUserDetails.getPassword(), userDetails.getPassword());
    assertEquals(expectedUserDetails.getUsername(), userDetails.getUsername());
    assertEquals(expectedUserDetails.isAccountNonExpired(), userDetails.isAccountNonExpired());
    assertEquals(expectedUserDetails.isAccountNonLocked(), userDetails.isAccountNonLocked());
    assertEquals(
        expectedUserDetails.isCredentialsNonExpired(),
        expectedUserDetails.isCredentialsNonExpired());
    assertEquals(expectedUserDetails.isEnabled(), userDetails.isEnabled());
    assertTrue(
        HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
            expectedUserDetails.getAuthorities(), userDetails.getAuthorities()));

    try {
      userDetails = userDetailsServiceWrapper.loadUserByUsername("USERNAME_NOT_FOUND_EXCEPTION");
      fail("testLoadUserByUsername() - UsernameNotFoundException did not bubble up!");
    } catch (UsernameNotFoundException e) {
    }
  }
  /**
   * 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 OutOfBandAuthenticationToken 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 rawUserDetails, OutOfBandAuthenticationToken auth) {
    String eMail = auth.getEmail();
    if (eMail == null) {
      logger.warn("OutOfBand attributes did not include an e-mail address! ");
      throw new UsernameNotFoundException("email address not supplied in OutOfBand attributes");
    }
    eMail = OutOfBandAuthenticationProvider.normalizeMailtoAddress(eMail);
    String mailtoDomain = OutOfBandAuthenticationProvider.getMailtoDomain(eMail);

    UserDetails userDetails = rawUserDetails;

    Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();

    authorities.addAll(userDetails.getAuthorities());
    // add the AUTH_OUT_OF_BAND granted authority,
    authorities.add(new SimpleGrantedAuthority(GrantedAuthorityName.AUTH_OUT_OF_BAND.toString()));

    // attempt to look user up in registered users table...
    String username = null;
    UserDetails partialDetails = null;
    boolean noRights = false;
    try {
      partialDetails = wrappingUserDetailsService.loadUserByUsername(eMail);
      // found the user in the table -- fold in authorizations and get uriUser.
      authorities.addAll(partialDetails.getAuthorities());
      // users are blacklisted by registering them and giving them no rights.
      noRights = partialDetails.getAuthorities().isEmpty();
      username = partialDetails.getUsername();
    } catch (Exception e) {
      logger.warn(
          "OutOfBand attribute e-mail: "
              + eMail
              + " did not match any known e-mail addresses! "
              + e.getMessage());
      throw new UsernameNotFoundException("account not recognized");
    }

    AggregateUser trueUser =
        new AggregateUser(
            username,
            partialDetails.getPassword(),
            UUID.randomUUID().toString(), // junk...
            mailtoDomain,
            partialDetails.isEnabled(),
            partialDetails.isAccountNonExpired(),
            partialDetails.isCredentialsNonExpired(),
            partialDetails.isAccountNonLocked(),
            authorities);
    if (noRights
        || !(trueUser.isEnabled()
            && trueUser.isAccountNonExpired()
            && trueUser.isAccountNonLocked())) {
      logger.warn("OutOfBand attribute e-mail: " + eMail + " account is blocked! ");
      throw new UsernameNotFoundException("account is blocked");
    }

    return new OutOfBandAuthenticationToken(trueUser, trueUser.getAuthorities(), auth.getEmail());
  }
示例#3
0
 /** Private copy constructor. */
 private WikiUserDetailsImpl(UserDetails userDetails) {
   this.username = userDetails.getUsername();
   this.password = userDetails.getPassword();
   this.enabled = userDetails.isEnabled();
   this.accountNonExpired = userDetails.isAccountNonExpired();
   this.credentialsNonExpired = userDetails.isCredentialsNonExpired();
   this.accountNonLocked = userDetails.isAccountNonLocked();
   this.setAuthorities(userDetails.getAuthorities());
 }
  @Override
  public Authentication authenticate(final Authentication authentication)
      throws AuthenticationException {
    if (!supports(authentication.getClass())) {
      return null;
    }

    if (authentication.isAuthenticated() || authentication.getCredentials() == null) {
      return authentication;
    }

    final String code = (String) ((MailAuthenticationToken) authentication).getCredentials();

    UserDetails user =
        new TransactionTemplate(transactionManager)
            .execute(
                new TransactionCallback<UserDetails>() {
                  @Override
                  public UserDetails doInTransaction(TransactionStatus transactionStatus) {
                    Account account = accountService.findByCode(code);
                    if (account != null) {
                      account.setEnabled(true);
                      return userDetailsService.loadUserByUsername(account.getMail());
                    } else {
                      return null;
                    }
                  }
                });

    if (user != null) {
      if (!user.isAccountNonLocked()) {
        throw new LockedException("User account is locked.", user);
      }

      if (!user.isEnabled()) {
        throw new DisabledException("User account is disabled.", user);
      }

      if (!user.isAccountNonExpired()) {
        throw new AccountExpiredException("User account has expired.");
      }

      return new MailAuthenticationToken(code, user, user.getAuthorities());
    } else {
      throw new BadCredentialsException("Can't find user account by code.");
    }
  }