Приложение Jhipster не подключается к серверу LDAP - PullRequest
0 голосов
/ 25 февраля 2020

Я изменил код точно в соответствии с документацией jhipster для аутентификации ldap с небольшими изменениями. Но он все еще подключается к базе данных вместо сервера ldap. Когда я отлаживаю приложение, authentication.getprinciple () не попадает в LdapUserDetails, вместо этого оно входит в UserDetails и продолжает повторять неверные учетные данные с моими учетными данными.

SecurityUtil. java

public static Optional<String> getCurrentUserLogin() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    return Optional.ofNullable(extractPrincipal(securityContext.getAuthentication()));
}

private static String extractPrincipal(Authentication authentication) {
    if (authentication == null) {
        return null;
    } else if (authentication.getPrincipal() instanceof UserDetails) {
        UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
        return springSecurityUser.getUsername();
    } else if (authentication.getPrincipal() instanceof String) {
        return (String) authentication.getPrincipal();
    } else if (authentication.getPrincipal() instanceof LdapUserDetails) {
        LdapUserDetails ldapUser = (LdapUserDetails) authentication.getPrincipal();
        return ldapUser.getUsername();
    }
    return null;
}

/**
 * Get the login of the current user.
 *
 * @return the login of the current user.
 */
public static UserDTO getCurrentUserLoginDetails() {
    UserDTO userDTO = new UserDTO();
    SecurityContext securityContext = SecurityContextHolder.getContext();

    userDTO.setLogin(getCurrentUserLogin().get());
    Set<String> authorities = new HashSet<>();
    for (GrantedAuthority grantedAuthority : securityContext.getAuthentication().getAuthorities()) {
        authorities.add(grantedAuthority.getAuthority());
    }
    userDTO.setAuthorities(authorities);

    return userDTO;
}
/**
 * Get the JWT of the current user.
 *
 * @return the JWT of the current user.
 */
public static Optional<String> getCurrentUserJWT() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    return Optional.ofNullable(securityContext.getAuthentication())
            .filter(authentication -> authentication.getCredentials() instanceof String)
            .map(authentication -> (String) authentication.getCredentials());
}

/**
 * Check if a user is authenticated.
 *
 * @return true if the user is authenticated, false otherwise.
 */
public static boolean isAuthenticated() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    return authentication != null
            && getAuthorities(authentication).noneMatch(AuthoritiesConstants.ANONYMOUS::equals);
}

/**
 * If the current user has a specific authority (security role).
 * <p>
 * The name of this method comes from the {@code isUserInRole()} method in the
 * Servlet API.
 *
 * @param authority the authority to check.
 * @return true if the current user has the authority, false otherwise.
 */
public static boolean isCurrentUserInRole(String authority) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    return authentication != null && getAuthorities(authentication).anyMatch(authority::equals);
}

private static Stream<String> getAuthorities(Authentication authentication) {
    return authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority);
}

SecurityConfiguration. java

@Inject
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.ldapAuthentication().userSearchBase("OU=usersAndGroups") // don't add the base
            .userSearchFilter("(cn={0})")
            .groupSearchBase("....") // don't add the base
            .groupSearchFilter("member={0}").groupRoleAttribute("cn").contextSource(getContextSource());
}

@Bean
public LdapContextSource getContextSource() {
    LdapContextSource contextSource = new LdapContextSource();
    contextSource.setUrl("URL");
    contextSource.setBase("");
    contextSource.setUserDn("");
    contextSource.setPassword("mmmmmmmm");
    contextSource.afterPropertiesSet(); // needed otherwise you will have a NullPointerException in spring

    return contextSource;
}

CustomAuthenticationManager. Java

@Component
public class CustomAuthenticationManager implements AuthenticationManager {

LdapAuthenticationProvider provider = null;

private static final Logger log = LoggerFactory.getLogger(CustomAuthenticationManager.class);

private final UserRepository userRepository;

@Autowired
private final LdapContextSource ldapContextSource;

public CustomAuthenticationManager(UserRepository userRepository, LdapContextSource ldapContextSource) {
    System.out.println("-------------------------------------------------------------------------------------------------------");
    this.userRepository = userRepository;
    this.ldapContextSource = ldapContextSource;
}

@Override
public Authentication authenticate(Authentication authentication) {
    log.debug("AUTHENTICATION Login" + authentication.getName());
    log.debug("AUTHENTICATION Password" + authentication.getCredentials().toString());

    BindAuthenticator bindAuth = new BindAuthenticator(ldapContextSource);
    FilterBasedLdapUserSearch userSearch = new FilterBasedLdapUserSearch(
            "", "(uid={0})",
            ldapContextSource);
    try{
        bindAuth.setUserSearch(userSearch);
        bindAuth.afterPropertiesSet();
    } catch (Exception ex) {
        java.util.logging.Logger.getLogger(CustomAuthenticationManager.class.getName()).log(Level.SEVERE, null, ex);
    }
    provider = new LdapAuthenticationProvider(bindAuth);
    provider.setUserDetailsContextMapper(new UserDetailsContextMapper() {
        @Override
        public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> clctn) {
            Optional<User> isUser = userRepository.findOneWithAuthoritiesByLogin(username);
            final User user = isUser.get();
            Set<Authority> userAuthorities = user.getAuthorities();
            Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            for(Authority a: userAuthorities){
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(
                        a.getName());
                grantedAuthorities.add(grantedAuthority);
            }
              return new org.springframework.security.core.userdetails.User(
                username, "1" , grantedAuthorities);    
        }

        @Override
        public void mapUserToContext(UserDetails ud, DirContextAdapter dca) {

        }
    });
    return provider.authenticate(authentication);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...