Skip to content

Changes Related to Ldap Caching #281

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions publish-service/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,16 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
<version>${springboot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.ericsson.eiffel.remrem.publish.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
public class CacheConfig {

@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager(new String[]{"ldapUserDetailsCache"});
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package com.ericsson.eiffel.remrem.publish.config;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import ch.qos.logback.classic.Logger;

@Service
public class CustomLdapUserDetailsService implements UserDetailsService{


@Value("${activedirectory.rootDn}")
private String rootDn;

@Autowired
private LdapTemplate ldapTemplate;

@Autowired
private CacheManager cacheManager;

private Logger log = (Logger) LoggerFactory.getLogger(CustomLdapUserDetailsService.class);

@Cacheable(value = "ldapUserDetailsCache", key = "#username")
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Cache cache = cacheManager.getCache("ldapUserDetailsCache");
if (cache != null && cache.get(username) != null) {
return cache.get(username, UserDetails.class);
} else {
log.info("---------------------at 41--------------");
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
String username1 = userDetails.getUsername();
String password = userDetails.getPassword();
log.info("------------ at 46------------" + username+" "+ password);
log.info("------------------------- 47----------- "+ userDetails);
cacheManager.getCache("ldapUserDetailsCache").put(username, userDetails);
return userDetails;
}
}

/*
* private UserDetails mapToUserDetails(Attributes attributes) { // Extract and map attributes
* to UserDetails object // Example: String username = null;
* log.info("--------------- at 65----------------- "); try { username =
* attributes.get("sAMAccountName").get().toString(); } catch(NamingException e) {
*
* } // System.out.println("------------------------ at 56 ------------- "+ username); // String
* password = attributes.get("userPassword").get().toString(); // ...
*
* // Create and return UserDetails object // Example: return User.withUsername(username) //
* .password(password) .roles("USER") .build();
*
* // Implement attribute extraction and UserDetails creation logic based on your LDAP schema //
* return null; }
*/

/*
* @Override public UserDetails loadUserByUsername(String username) throws
* UsernameNotFoundException { Cache cache = cacheManager.getCache("ldapUserDetailsCache"); if
* (cache != null && cache.get(username) != null) { return cache.get(username,
* UserDetails.class); } else { Authentication authentication =
* SecurityContextHolder.getContext().getAuthentication(); String authenticatedUsername =
* authentication.getName();
*
* UserDetails userDetails = getUserDetailsByUsername(authenticatedUsername);
*
* cache.put(authenticatedUsername, userDetails);
*
* return userDetails;
*
* // throw new UsernameNotFoundException("User not found"); } } public UserDetails
* getUserDetailsByUsername(String username) { // Assuming 'cn' is the attribute for the
* username in LDAP String ldapQuery = "(cn=" + username + ")";
*
* try { return ldapTemplate.search( "", // Base DN for the search ldapQuery, // LDAP filter
* (AttributesMapper<UserDetails>) attributes -> { // Map LDAP attributes to UserDetails object
* // Example mapping; adapt based on your LDAP schema String ldapUsername =
* attributes.get("cn").get().toString(); // String ldapPassword = ""; // Fetch password
* attribute // Other attribute mappings as needed
*
* return org.springframework.security.core.userdetails.User .withUsername(ldapUsername) //
* .password(ldapPassword) .roles("USER") // Set user roles based on LDAP attributes // Other
* attribute settings as needed .build(); }).stream().findFirst().orElse(null); // Fetch the
* first matching entry } catch (Exception e) { throw new
* UsernameNotFoundException("User not found");
*/

}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.ldap.core.support.BaseLdapPathContextSource;
Expand All @@ -29,6 +30,7 @@
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
* This class is used to enable the ldap authentication based on property
Expand Down Expand Up @@ -70,7 +72,10 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
public Integer getTimeOut() {
return ldapTimeOut;
}

//
@Autowired
private CustomLdapUserDetailsService customLdapUserDetailsService;

@Autowired
private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;

Expand All @@ -82,11 +87,25 @@ protected void configureGlobal(AuthenticationManagerBuilder auth) throws Excepti
managerPassword.substring(1, managerPassword.length() - 1), jasyptKey);
}
LOGGER.debug("LDAP server url: " + ldapUrl);
auth.ldapAuthentication()
auth
.userDetailsService(customLdapUserDetailsService)
.and()
.ldapAuthentication()
.userSearchFilter(userSearchFilter)
.contextSource(ldapContextSource());
}


// @Override
// protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// auth.userDetailsService(customLdapUserDetailsService); }


// @Bean
// public UserDetailsService userDetailsService() {
// return new CustomLdapUserDetailsService();
// }

public BaseLdapPathContextSource ldapContextSource() {
LdapContextSource ldap = new LdapContextSource();
ldap.setUrl(ldapUrl);
Expand All @@ -112,5 +131,16 @@ protected void configure(HttpSecurity http) throws Exception {
.and()
.csrf()
.disable();
// .sessionManagement()
// .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) // Create session if required
// .sessionFixation().migrateSession() // Migrate session to prevent fixation attacks
// .maximumSessions(1) // Allow only one session per user
// .maxSessionsPreventsLogin(false) // Allows multiple logins for the same user
// .expiredUrl("/login?expired") // Redirect to this URL on session expiration
// .and()
// .and()
// .logout()
// .invalidateHttpSession(true)
// .deleteCookies("JSESSIONID");
}
}
6 changes: 6 additions & 0 deletions publish-service/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ debug: false

spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER

# Cache names
spring.cache.cache-names=ldapUserDetailsCache

# Ehcache specific settings
spring.cache.type=ehcache

#Logging configurations
logging.level.root: INFO
logging.level.org.springframework.web: INFO
Expand Down