SecurityConfiguration

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Autowired
@Qualifier(“customUserDetailsService”)
UserDetailsService userDetailsService;

@Autowired
PersistentTokenRepository tokenRepository;

@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
auth.authenticationProvider(customAuthenticationProvider());

}

@Override
protected void configure(HttpSecurity http) throws Exception {

http.anonymous().disable()
.authorizeRequests().antMatchers(“/”)
.access(“hasRole(‘USER’)”)

.antMatchers(“/newSecurity” )
.access(“hasRole(‘SECURITY GUARD’)”)

.antMatchers(“/edit-user-*”,”/usersList” ,”/userProfilesList”)
.access(“hasRole(‘ADMIN’)”)

.antMatchers(“/download-document-*”, “/delete-request-*”,”/edit-request-*” )
.access(“hasRole(‘USER’)”)

.and().formLogin().loginPage(“/login”)
.loginProcessingUrl(“/login”).usernameParameter(“ssoId”).passwordParameter(“password”).and()
.rememberMe().rememberMeParameter(“remember-me”).tokenRepository(tokenRepository)
.tokenValiditySeconds(18400).and().csrf().and().exceptionHandling().accessDeniedPage(“/Access_Denied”);
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Bean
public CustomAuthenticationProvider customAuthenticationProvider() {
CustomAuthenticationProvider customAuthenticationProvider = new CustomAuthenticationProvider();

return customAuthenticationProvider;
}

@Bean
public PersistentTokenBasedRememberMeServices getPersistentTokenBasedRememberMeServices() {
PersistentTokenBasedRememberMeServices tokenBasedservice = new PersistentTokenBasedRememberMeServices(
“remember-me”, userDetailsService, tokenRepository);
return tokenBasedservice;
}

@Bean
public AuthenticationTrustResolver getAuthenticationTrustResolver() {
return new AuthenticationTrustResolverImpl();
}

}


CustomUserDetailsService

import java.util.ArrayList;
import java.util.List;

import com.abc.dcim.common.Utils;
import com.abc.dcim.controller.AppController;
import com.abc.dcim.model.AppUser;
import com.abc.dcim.model.UserProfile;
import com.abc.dcim.service.UserService;
import com.abc.dcim.uiinterfaces.LoginDetailsUi;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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 org.springframework.transaction.annotation.Transactional;

@Service(“customUserDetailsService”)
public class CustomUserDetailsService implements UserDetailsService,LoginDetailsUi{

static final Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);

@Autowired
private UserService userService;

private String pwd;

private boolean ldapStatus=false;

@Transactional(readOnly=true)
public UserDetails loadUserByUsername(String ssoId)
throws UsernameNotFoundException {

if(ldapStatus){
logger.info(“User not found in AD”);
throw new UsernameNotFoundException(“Username not found”);
}

if(ssoId.split(“:”).length>0){
ssoId = ssoId.split(“:”)[1];
}

AppUser user = userService.findBySSO(ssoId);
logger.info(“User : {}”, user);
if(user==null){
logger.info(“User not found”);
throw new UsernameNotFoundException(“Username not found”);
}
return new org.springframework.security.core.userdetails.User(user.getSsoId(), pwd,getGrantedAuthorities(user));

}

private List<GrantedAuthority> getGrantedAuthorities(AppUser user){
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

for(UserProfile userProfile : user.getUserProfiles()){
logger.info(“UserProfile : {}”, userProfile);
authorities.add(new SimpleGrantedAuthority(“ROLE_”+userProfile.getName()));
}
logger.info(“authorities : {}”, authorities);
return authorities;
}

@Override
public String getUserEnteredPassword(String pwd) {
this.pwd=pwd;
return this.pwd;
}

@Override
public boolean getAuthenticationFromLDAP(boolean status) {
// TODO Auto-generated method stub
this.ldapStatus =status;
return ldapStatus;
}

}


LoginDetailsUi

public interface LoginDetailsUi {

String getUserEnteredPassword(String pwd);

boolean getAuthenticationFromLDAP(boolean status);

}


CustomAuthenticationProvider

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.configurers.ldap.LdapAuthenticationProviderConfigurer.ContextSourceBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import com.abc.dcim.common.Utils;
import com.abc.dcim.uiinterfaces.LoginDetailsUi;

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

public static final String CONTEXT_FACTORY= “com.sun.jndi.ldap.LdapCtxFactory”;

public static final String ACTIVE_D_URL= “ldap://10.100.100.100:389″;

//functional IDDCIMAD
public static final String USERNAME =”tharakadinesh@abc.com”;

//encrypted functional ID PSWD
public static final String PASSWORD =”da38ZfYL/r7i/U3ggU93gw==”;

@Autowired
private UserService userService;

@Autowired
private SupportStaffService supportStaffService;

@Autowired
private LoginDetailsUi CustomUserDetailsService;

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

String name = authentication.getName().split(“:”)[1];

if(authentication.getCredentials()!=null){
String password = authentication.getCredentials().toString();//user enters passwd
CustomUserDetailsService.getUserEnteredPassword(password);

    if (authenticateAgainstThirdPartySystem(name,password,authentication.getName().split(“:”)[0])) {
// use the credentials
// and authenticate against the third-party system
return null;
} else {

return null;
}

}
return null;
}

private boolean authenticateAgainstThirdPartySystem(String ssoId, String pwd, String reg) {
// TODO Auto-generated method stub
ssoId = ssoId+”@abc.com”;

LdapContext ldapPer = getLdapContext(ssoId,pwd,reg);

return getUserBasicAttributes(Utils.findUserName(ssoId), pwd,reg, ldapPer);
}

@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}

public boolean getUserBasicAttributes(String username,String password, String reg, LdapContext ctx) {
try {

if(ctx==null){
//error msg for login
CustomUserDetailsService.getAuthenticationFromLDAP(true);
}else{
CustomUserDetailsService.getAuthenticationFromLDAP(false);
}

SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);

String[] attrIDs = { “distinguishedName”, “sn”, “givenname”, “mail”, “telephonenumber”, “memberOf”, “CN”,”department” };
constraints.setReturningAttributes(attrIDs);

NamingEnumeration<?> answer = ctx.search(“DC=”+reg+”,DC=1bank,DC=abc,DC=com”,
“sAMAccountName=” + username, constraints);

    if (answer.hasMore()) {

Attributes attrs = ((SearchResult) answer.next()).getAttributes();

System.out.println(“distinguishedName ” + attrs.get(“distinguishedName”));
System.out.println(“givenname ” + attrs.get(“givenname”));
System.out.println(“sn ” + attrs.get(“sn”));
System.out.println(“mail ” + attrs.get(“mail”));
System.out.println(“memberof ” + attrs.get(“memberof”));

String emailId =attrs.get(“mail”).get().toString();
String dep =attrs.get(“department”)==null?””:attrs.get(“department”).get().toString();
String contact =attrs.get(“telephonenumber”)==null?””:attrs.get(“telephonenumber”).get().toString();

return true;
} else {
CustomUserDetailsService.getAuthenticationFromLDAP(true);
throw new Exception(“Invalid User”);
}

} catch (Exception ex) {
CustomUserDetailsService.getAuthenticationFromLDAP(true);
ex.printStackTrace();
}
return false;
}

public LdapContext getLdapContext(String userName,String password,String reg) {
LdapContext ctx = null;

try {
Hashtable<String, String> env = new Hashtable<String, String>();

env.put(Context.INITIAL_CONTEXT_FACTORY, CONTEXT_FACTORY);
env.put(Context.SECURITY_AUTHENTICATION, “Simple”);
env.put(Context.SECURITY_PRINCIPAL, userName);
env.put(Context.SECURITY_CREDENTIALS, password);
env.put(Context.SECURITY_PROTOCOL, “TLSv1.2”);
env.put(Context.PROVIDER_URL, ACTIVE_D_URL);
ctx = new InitialLdapContext(env, null);

         System.out.println(“Connection Successful”);

} catch (NamingException nex) {
System.out.println(“LDAP Connection: FAILED”);
nex.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}

return ctx;
}

public static String getPassword(){

try {
Utils utils = new Utils();
return utils.decrypt(PASSWORD);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

public String checkNull(Attribute attribute) throws NamingException{

if(attribute==null){
return “”;
}else{
return attribute.get().toString();
}
}

}