Spring Security 3 custom remember me - spring-security

i want to change remember me request parameter to override default parameter '_spring_security_remember_me'
and custom my remember me service to replace <remember-me /> namespace config.
so i config my remember me service:
<bean id="rememberMeServices" class="org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices">
<property name="key" value="MY_REMEMBER_ME_KEY" />
<property name="cookieName" value="MY_REMEMBER_ME_COOKIE" />
<property name="parameter" value="remember" />
<property name="tokenValiditySeconds" value="1209600" />
<property name="useSecureCookie" value="true" />
<property name="userDetailsService" ref="userDetailsService" />
<property name="alwaysRemember" value="false" />
</bean>
namespace config:
<intercept-url pattern="/secure/index" access="ROLE_ADMIN" />
<remember-me services-ref="rememberMeServices"/>
when i run application and login. i find cookie is created then i close my ie and reopen.
entry the path '/secure/index', tomcat show me access is denied .
but i revert to Spring Security default config , all is ok.
i debug code find
RememberMeAuthenticationFilter#doFilter
...
Authentication rememberMeAuth = rememberMeServices.autoLogin(request, response);
...
//autoLogin(request, response) method code.
String rememberMeCookie = extractRememberMeCookie(request);
...
protected String extractRememberMeCookie(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if ((cookies == null) || (cookies.length == 0)) {
return null;
}
for (int i = 0; i < cookies.length; i++) {
if (cookieName.equals(cookies[i].getName())) {
return cookies[i].getValue();
}
}
return null;
}
in method extractRememberMeCookie(request), code request.getCookies() always return null when i use my custom remember me service, but i revert Spring Security default namespace <remember-me/> and do the same(clean Cookies - login - close ie - reopen - entry path '/secure/index'), i also find cookie is create .
and i debug the code i find request.getCookies() return the cookie name 'SPRING_SECURITY_REMEMBER_ME_COOKIE' and authentication successfully.
need other config to remember me authentication ?
but i don't know , would someone help me.

Your <remember-me /> still need key
this should be
<remember-me key="MY_REMEMBER_ME_KEY" services-ref="rememberMeServices"/>

As per the documentation of TokenBasedRememberMeServices,
An org.springframework.security.core.userdetails.UserDetailsService is
required by this implementation, so that it can construct a valid
Authentication from the returned
org.springframework.security.core.userdetails.UserDetails. This is
also necessary so that the user's password is available and can be
checked as part of the encoded cookie.
Perhaps your configuration is incorrect/incomplete.

This is actually an old post. But I just had the issue request.getCookies() null w/ Spring 4.
I've removed useSecureCookie = true to fix it.

Related

Spring Security: Getting error "The server understood the request but refuses to authorize it"

While running the application using Spring Security, I am getting below error on all browsers:
"The server understood the request but refuses to authorize it"
I tried by changing Roles from "ROLE_ADMIN" to "ROLE_USER" in "spring-security.xml" file.
Below is "spring-security.xml"
<http auto-config="true">
<intercept-url pattern ="/admin" access = "hasRole('ROLE-USER')"/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name = "abc" password = "xyz" authorities="hasRole('ROLE-USER')" />
</user-service>
</authentication-provider>
</authentication-manager>
Below is SpringController Class:
#Controller
public class SpringController {
#RequestMapping(value = "/")
public String homePage() {
return "HomePage";
}
#RequestMapping(value="/admin", method=RequestMethod.GET)
public String loginPage() {
return "login";
}
HomePage.jsp and login.jsp pages are loaded property but after passing credentials on login.jsp getting error:
HTTP Status 403 – Forbidden
Type: Status Report
Message: Access is denied
Description: The server understood the request but refuses to
authorize it.
Apache Tomcat/7.0.90
403 is a very generic error code. I was facing the same issue but after making some changes I am able to make it work. Still not sure if the problem was with password encryption or configuration of form-login tag.
<security:http auto-config="true" >
<security:intercept-url pattern="/login*" access="isAnonymous()" />
<security:intercept-url pattern="/**" access="isAuthenticated()"/>
<security:form-login login-page="/login" login-processing-url="/login-user" authentication-failure-url="/login?error=true" />
<security:csrf disabled="true" />
<security:logout logout-success-url="/" />
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="admin" password="{noop}admin" authorities="ROLE_USER" />
</security:user-service>
</security:authentication-provider >
</security:authentication-manager>
Ignore the security: prefix in the tags.
{noop} in front of the password ensures that I am not using any encryption for the password.
Controller to show login JSP
#Controller
#RequestMapping("/login")
public class LoginController {
#RequestMapping(value = { "/", "" }, method = { RequestMethod.GET})
public String login(HttpServletRequest request) {
System.out.println("LoginController.login() "+request.getRequestURI());
return "login";
}
}
Form action
<form name='loginForm' action="login-user" method='POST'>
I got this issue but not while using spring. We were hosting two instances of our own in house application on the same server but using two different ports. Login to one instance was okay, however login to the other one from the same browser (another tab) caused the error above to be thrown from tomcat, preceded with this message "CSRF nonce validation failed".
The workaround I did is to login to the other instance from different browser. I know that this is not a fix but it may help if you have a situation similar to mine
This happens because you use normal <form> tags with spring security, while it checks for CSRF attacks.
The solution is:
Add CSRF hidden field with each <form> tag
<form action="..." method="POST">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
</form>
Or use spring MVC <form:form> tags which include this hidden field automtically (Recommended)
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<form:form action="..." method="POST">
</form:form>
This also happened with me when I accidentally launched two instances of my application on different tomcat servers. I resolved it by removing the working directories of the application in my webapps and work folders, and restarting the server.
use <form:form> tags when you're dealing with spring security, instead of manually adding the CSRF token for each forms as below
<form:form action="", method="">
</form:form>

Redirect to Previous url after TIMEOUT

I am using Spring 3.1 version.
I have implemented spring security for login to my web portal. It works fine except for one issue. I have set session timeout to 2 min.
Once timeout happens and then user click any URL, It gets redirected to logout page. But when user re authenticates, user directly lands on the home page which is default target URL instead of last access page.
Like if user is accessed /home/editproduct then after timeout & when he again reautenticate he should be accessed to the home/editproduct instead of only /home page.
i am using spring with JSON & AJAX call.
<bean id="myNePublicUserNamePasswordAuthFilter"
class="com.ne.mynelson.authentication.publicuser.MyNePublicUserPasswordAuthFilter">
<property name="filterProcessesUrl" value="/service/json_authentication_check"></property>
<property name="authenticationManager" ref="myNePublicUserAuthenticationManager" />
<property name="authenticationFailureHandler" ref="failureHandler" />
<property name="authenticationSuccessHandler" ref="successHandler" />
<property name="authenticationInputProcessor" ref="myNePublicUserAuthInputProcessor"></property>
</bean>
<bean id="successHandler"
class="com.ne.mynelson.authentication.publicuser.MyNePublicUserAuthSuccessHandler">
<property name="authHandlerView" ref="authHandlerView"></property>
<property name="sessionRegistry" ref="sessionRegistry"></property>
<property name="publicLoginManager" ref="publicLoginManager"></property>
</bean>
EDIT: For SessionManagementFilter
You need to implement the InvalidSessionStrategy, override the onInvalidSessionDetected method, just like SimpleRedirectInvalidSessionStrategy, but before redirect, you need to create a new session, and save the request to session.
HttpSession session = request.getsession(false);
if (session != null) {
// for creating a new session
session.invalidate();
}
DefaultSavedRequest savedRequest = new DefaultSavedRequest(request,
new PortResolverImpl());
request.getSession(true).setAttribute("SPRING_SECURITY_SAVED_REQUEST", savedRequest);
redirectStrategy.sendRedirect(request, response, destinationUrl);
and then inject this bean to SessionManagementFilter.
EDIT: For ConcurrentSessionFilter
If you use the concurrentSessionFilter, you can implement SessionInformationExpiredStrategy, just like SimpleRedirectSessionInformationExpiredStrategy, and in the method onExpiredSessionDetected, still do the same thing like I post above, before redirect, create new session, and put the save request to new session, you can get the requestby event.getRequest(), then inject this sessionInfomationExpiredStrategy to concurrentSessionFilter.
public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException {
logger.debug("Redirecting to '" + destinationUrl + "'");
DefaultSavedRequest savedRequest = new DefaultSavedRequest(event.getRequest(),
new PortResolverImpl());
request.getSession(true).setAttribute("SPRING_SECURITY_SAVED_REQUEST", savedRequest);
redirectStrategy.sendRedirect(event.getRequest(), event.getResponse(), destinationUrl);
}
Finally , Using SavedRequestAwareAuthenticationSuccessHandler instead of SimpleUrlAuthenticationSuccessHandler. It will try to get the request target url and then redirect to the saved URL.

How to dynamically decide <intercept-url> access attribute value in Spring Security?

In Spring Security we use the intercept-url tag to define the access for URLs as below:
<intercept-url pattern="/**" access="ROLE_ADMIN" />
<intercept-url pattern="/student" access="ROLE_STUDENT" />
This is hard coded in applicationContext-security.xml. I want to read the access values from a database table instead. I have defined my own UserDetailsService and I read the roles for the logged in user from the database. How do I assign these roles to the URL patterns during runtime?
The FilterInvocationSecurityMetadataSourceParser class in Spring-security (try Ctrl/Cmd+Shift+T in STS with the source code) parses the intercept-url tags and creates instances of ExpressionBasedFilterInvocationSecurityMetadataSource, that extends DefaultFilterInvocationSecurityMetadataSource that implements FilterInvocationSecurityMetadataSource that extends SecurityMetadataSource.
What I did is to create a custom class that implements FilterInvocationSecurityMetadataSource, OptionsFromDataBaseFilterInvocationSecurityMetadataSource. I used DefaultFilterInvocationSecurityMetadataSource as base to use urlMatcher, to implement the support() method and something like that.
Then you must to implement these methods:
Collection getAttributes(Object object), where you can access to database, searching for the 'object' being secured (normally the URL to access) to obtain the allowed ConfigAttribute's (normally the ROLE's)
boolean supports(Class clazz)
Collection getAllConfigAttributes()
Be careful with the later, because it's called at startup and maybe is not well configured at this time (I mean, with the datasources or persistence context autowired, depending on what are you using). The solution in a web environment is to configure the contextConfigLocation in the web.xml to load the applicationContext.xml before the applicationContext-security.xml
The final step is to customize the applicationContext-security.xml to load this bean.
For doing that, I used regular beans in this file instead of the security namespace:
<beans:bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy">
<filter-chain-map path-type="ant">
<filter-chain pattern="/images/*" filters="none" />
<filter-chain pattern="/resources/**" filters="none" />
<filter-chain pattern="/**" filters="
securityContextPersistenceFilter,
logoutFilter,
basicAuthenticationFilter,
exceptionTranslationFilter,
filterSecurityInterceptor"
/>
</filter-chain-map>
</beans:bean>
You have to define all the related beans. For instance:
<beans:bean id="filterSecurityInterceptor" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
<beans:property name="authenticationManager" ref="authenticationManager"></beans:property>
<beans:property name="accessDecisionManager" ref="affirmativeBased"></beans:property>
<beans:property name="securityMetadataSource" ref="optionsFromDataBaseFilterInvocationSecurityMetadataSource"></beans:property>
<beans:property name="validateConfigAttributes" value="true"/></beans:bean>
I know that is not a well explained answer, but it's not as difficult as it seems.
Just use the spring source as base and you will obtain what you want.
Debugging with the data in your database, will help you a lot.
Actually, spring security 3.2 do not encourage to do this according to http://docs.spring.io/spring-security/site/docs/3.2.x/reference/htmlsingle/faq.html#faq-dynamic-url-metadata
but, it is possible (but not elegant) using http element in namespace with a custom accessDecisionManager..
The config should be:
<http pattern="/login.action" security="none"/>
<http pattern="/media/**" security="none"/>
<http access-decision-manager-ref="accessDecisionManager" >
<intercept-url pattern="/**" access="ROLE_USER"/>
<form-login login-page="/login.action"
authentication-failure-url="/login?error=1"
default-target-url="/console.action"/>
<logout invalidate-session="true" delete-cookies="JSESIONID"/>
<session-management session-fixation-protection="migrateSession">
<concurrency-control max-sessions="1" error-if-maximum-exceeded="true" expired-url="/login.action"/>
</session-management>
<!-- NO ESTA FUNCIONANDO, los tokens no se ponen en el request!
<csrf />
-->
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="test" password="test" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
<beans:bean id="accessDecisionManager" class="openjsoft.core.services.security.auth.CustomAccessDecisionManager">
<beans:property name="allowIfAllAbstainDecisions" value="false"/>
<beans:property name="decisionVoters">
<beans:list>
<beans:bean class="org.springframework.security.access.vote.RoleVoter"/>
</beans:list>
</beans:property>
</beans:bean>
The CustomAccessDecisionManager should be...
public class CustomAccessDecisionManager extends AbstractAccessDecisionManager {
...
public void decide(Authentication authentication, Object filter,
Collection<ConfigAttribute> configAttributes)
throws AccessDeniedException, InsufficientAuthenticationException {
if ((filter == null) || !this.supports(filter.getClass())) {
throw new IllegalArgumentException("Object must be a FilterInvocation");
}
String url = ((FilterInvocation) filter).getRequestUrl();
String contexto = ((FilterInvocation) filter).getRequest().getContextPath();
Collection<ConfigAttribute> roles = service.getConfigAttributesFromSecuredUris(contexto, url);
int deny = 0;
for (AccessDecisionVoter voter : getDecisionVoters()) {
int result = voter.vote(authentication, filter, roles);
if (logger.isDebugEnabled()) {
logger.debug("Voter: " + voter + ", returned: " + result);
}
switch (result) {
case AccessDecisionVoter.ACCESS_GRANTED:
return;
case AccessDecisionVoter.ACCESS_DENIED:
deny++;
break;
default:
break;
}
}
if (deny > 0) {
throw new AccessDeniedException(messages.getMessage("AbstractAccessDecisionManager.accessDenied",
"Access is denied"));
}
// To get this far, every AccessDecisionVoter abstained
checkAllowIfAllAbstainDecisions();
}
...
}
Where getConfigAttributesFromSecuredUris retrieve form DB de roles for the specific URL
I have kind of the same problem, basically I'd like to keep separate the list of intercept-url from the other springsecurity configuration section, the first to belong to the application configuration the latter to the product (core, plugin) configuration.
There is a proposal in the JIRA of spring, concerning this problem.
I don't want to give up to use the springsecurity namespace, so I was thinking to some possible solutions in order to deal with this.
In order to have the list of intercept-url dynamically created you have to inject the securitymetadatasource object in the FilterSecurityInterceptor.
Using springsecurity schema the instance of FilterSecurityInterceptor is created by the HttpBuilder class and there is no way to pass the securitymetadatasource as property defined in the schema configuration file, as less as using kind of workaround, which could be:
Define a custom filter, to be executed before FilterSecurityInterceptor, in this filter retrieving the instance FilterSecurityInterceptor (assuming a unique http section is defined) by the spring context and inject there the securitymetadatasource instance;
The same as above but in a HandlerInterceptor.
What do you think?
This the solution I've applied in order to split the list of intercept-url entries from the other spring security configuration.
<security:custom-filter ref="parancoeFilterSecurityInterceptor"
before="FILTER_SECURITY_INTERCEPTOR" />
........
<bean id="parancoeFilterSecurityInterceptor" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor" >
<property name="authenticationManager" ref="authenticationManager"/>
<property name="accessDecisionManager" ref="accessDecisionManager"/>
<property name="securityMetadataSource" ref="securityMetadataSource"/>
</bean>
The bean securityMetadataSource can be put either in the same configuration file or in another configuration file.
<security:filter-security-metadata-source
id="securityMetadataSource" use-expressions="true">
<security:intercept-url pattern="/admin/**"
access="hasRole('ROLE_ADMIN')" />
</security:filter-security-metadata-source>
Of course you can decide to implement your own securityMetadataSource bean by implementing the interface FilterInvocationSecurityMetadataSource.
Something like this:
<bean id="securityMetadataSource" class="mypackage.MyImplementationOfFilterInvocationSecurityMetadataSource" />
Hope this helps.
This is how it can be done in Spring Security 3.2:
#Configuration
#EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Bean
public SecurityConfigDao securityConfigDao() {
SecurityConfigDaoImpl impl = new SecurityConfigDaoImpl() ;
return impl ;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
/* get a map of patterns and authorities */
Map<String,String> viewPermissions = securityConfigDao().viewPermissions() ;
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry interceptUrlRegistry = http
.authorizeRequests().antMatchers("/publicAccess/**")
.permitAll();
for (Map.Entry<String, String> entry: viewPermissions.entrySet()) {
interceptUrlRegistry.antMatchers(entry.getKey()).hasAuthority(entry.getValue());
}
interceptUrlRegistry.anyRequest().authenticated()
.and()
...
/* rest of the configuration */
}
}
A simple solution that works for me.
<intercept-url pattern="/**/**" access="#{#customAuthenticationProvider.returnStringMethod}" />
<intercept-url pattern="/**" access="#{#customAuthenticationProvider.returnStringMethod}" />
customAuthenticationProvider is a bean
<beans:bean id="customAuthenticationProvider"
class="package.security.CustomAuthenticationProvider" />
in CustomAuthenticationProvider class create method:
public synchronized String getReturnStringMethod()
{
//get data from database (call your method)
if(condition){
return "IS_AUTHENTICATED_ANONYMOUSLY";
}
return "ROLE_ADMIN,ROLE_USER";
}

How/where can I manage Authentication at SecurityContext in pre-authentation Scenario

I wonder how/where can I manage Authentication at SecurityContext in pre-authentation Scenario.
I am using spring security 2.x to implement pre-authentation Scenario in my project. now, it patially work.
After user login by pre-authentation process, they can be authrozied with relevant roles, and are able to acecess resources which defined in security:filter.
e.g.
<security:filter-invocation-definition-source lowercase-comparisons="true" path-type="ant">
<security:intercept-url pattern="/resource/**" access="ROLE_ADMIN" />
In a some controller, I want to check principal in security content.
public abstract class AbstractUserAuthenticationController extends AbstractController
{
protected boolean isAuthenticated(String userName)
{
Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // where issue come up
But SecurityContextHolder.getContext().getAuthentication() always return null.
In addition, I also can not use secuiry tag in jsp to check if user has relative roles
<security:authorize ifNotGranted="ROLE_ADMIN">
no role found
</security:authorize>
Below shows the "filterChainProxy" I am using.
<bean id="filterChainProxy" class="org.springframework.security.util.FilterChainProxy">
<property name="filterInvocationDefinitionSource">
<value>
CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
PATTERN_TYPE_APACHE_ANT
/*subscri*=httpSessionContextIntegrationFilter,logoutFilter,j2eePreAuthenticatedProcessingFilter,securityContextHolderAwareRequestFilter,subscribeExceptionTranslationFilter,filterInvocationInterceptor
/**=httpSessionContextIntegrationFilter,logoutFilter,j2eePreAuthenticatedProcessingFilter,logoutFilter,rememberMeProcessingFilter,exceptionTranslationFilter,filterSecurityInterceptor
</value>
</property>
</bean>
<bean id="preAuthenticatedAuthenticationProvider" class="org.springframework.security.providers.preauth.PreAuthenticatedAuthenticationProvider">
<property name="preAuthenticatedUserDetailsService" ref="preAuthenticatedUserDetailsService" />
</bean>
<bean id="preAuthenticatedUserDetailsService" class="demo.project.security.auth.RsaAuthenticationUserDetailsService" >
<property name="userService" ref="userService" />
</bean>
<bean id="j2eePreAuthFilter" class="demo.project.security.filter.AutoLoginFilter">
<property name="authenticationManager" ref="authenticationManager" />
<property name="userService" ref="userService" />
</bean>
I think I need to set Authentication to SecurityContext in somewhere, But I do not know where/where.
What I am missing? Can anyone provide me some clues?
Thanks!
Ian
You should use SecurityContextHolder.setContext method to store your SecurityContext prior to getting it back.
The simplest way for doing this is just SecurityContextHolder.setContext(new SecurityContextImpl()).

Spring LDAP - bind for successful connection

I'm trying to authenticate and then query our corporate LDAP using Spring LDAP and Spring security. I managed to make authentication work but when I attempt to run search I always get the following exception
In order to perform this operation a successful bind must be completed on the connection
After much research I have a theory that after I authenticate and before I can query I need to bind to connection. I just don't know what and how?
Just to mention - I can successfully browse and search our LDAP using JXplorer so my parameters are correct.
Here's section of my securityContext.xml
<security:http auto-config='true'>
<security:intercept-url pattern="/reports/goodbye.html"
access="ROLE_LOGOUT" />
<security:intercept-url pattern="/reports/**" access="ROLE_USER" />
<security:http-basic />
<security:logout logout-url="/reports/logout"
logout-success-url="/reports/goodbye.html" />
</security:http>
<security:ldap-server url="ldap://s140.foo.com:1389/dc=td,dc=foo,dc=com" />
<security:authentication-manager>
<security:authentication-provider ref="ldapAuthProvider">
</security:authentication-provider>
</security:authentication-manager>
<!-- Security beans -->
<bean id="contextSource" class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">
<constructor-arg value="ldap://s140.foo.com:1389/dc=td,dc=foo,dc=com" />
</bean>
<bean id="ldapAuthProvider"
class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider">
<constructor-arg>
<bean class="foo.bar.reporting.server.security.ldap.LdapAuthenticatorImpl">
<property name="contextFactory" ref="contextSource" />
<property name="principalPrefix" value="TD\" />
<property name="employee" ref="employee"></property>
</bean>
</constructor-arg>
<constructor-arg>
<bean class="foo.bar.reporting.server.security.ldap.LdapAuthoritiesPopulator" />
</constructor-arg>
</bean>
<!-- DAOs -->
<bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate">
<constructor-arg ref="contextSource" />
Here's code snippet from LdapAuthenticatorImpl that performs authentication. No problem here:
#Override
public DirContextOperations authenticate(final Authentication authentication) {
// Grab the username and password out of the authentication object.
final String name = authentication.getName();
final String principal = this.principalPrefix + name;
String password = "";
if (authentication.getCredentials() != null) {
password = authentication.getCredentials().toString();
}
if (!("".equals(principal.trim())) && !("".equals(password.trim()))) {
final InitialLdapContext ldapContext = (InitialLdapContext)
this.contextFactory.getContext(principal, password);
// We need to pass the context back out, so that the auth provider
// can add it to the Authentication object.
final DirContextOperations authAdapter = new DirContextAdapter();
authAdapter.addAttributeValue("ldapContext", ldapContext);
this.employee.setqId(name);
return authAdapter;
} else {
throw new BadCredentialsException("Blank username and/or password!");
}
}
And here's another code snippet from EmployeeDao with my futile attempt to query:
public List<Employee> queryEmployeesByName(String query)
throws BARServerException {
AndFilter filter = new AndFilter();
filter.and(new EqualsFilter("objectclass", "person"));
filter.and(new WhitespaceWildcardsFilter("cn", query));
try {
// the following line throws bind exception
List result = ldapTemplate.search(BASE, filter.encode(),
new AttributesMapper() {
#Override
public Employee mapFromAttributes(Attributes attrs)
throws NamingException {
Employee emp = new Employee((String) attrs.get("cn").get(),
(String) attrs.get("cn").get(),
(String) attrs.get("cn").get());
return emp;
}
});
return result;
} catch (Exception e) {
throw new BarServerException("Failed to query LDAP", e);
}
}
And lastly - the exception I'm getting
org.springframework.ldap.UncategorizedLdapException:
Uncategorized exception occured during LDAP processing; nested exception is
javax.naming.NamingException: [LDAP: error code 1 - 00000000: LdapErr:
DSID-0C090627, comment: In order to perform this operation a successful bind
must be completed on the connection., data 0, vece]; remaining name
'DC=TD,DC=FOO,DC=COM'
It looks like your LDAP is configured to not allow a search without binding to it (no anonymous bind). Also you have implemented PasswordComparisonAuthenticator and not BindAuthenticator to authenticate to LDAP.
You could try modifying your queryEmployeesByName() method to bind and then search, looking at some examples in the doc.
I'm going to accept #Raghuram answer mainly because it got me thinking in the right direction.
Why my code was failing? Turned out - the way I wired it I was trying to perform anonymous search which is prohibited by the system - hence the error.
How to rewire example above to work? First thing (and ugly thing at that) you need to provide user name and password of user that will be used to access the system. Very counterintuitive even when you login and authenticated, even if you are using BindAuthenticator system will not attempt to reuse your credentials. Bummer. So you need to stick 2 parameters into contextSource definition like so:
<bean id="contextSource" class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">
<constructor-arg value="ldap://foo.com:389/dc=td,dc=foo,dc=com" />
<!-- TODO - need to hide this or encrypt a password -->
<property name="userDn" value="CN=admin,OU=Application,DC=TD,DC=FOO,DC=COM" />
<property name="password" value="blah" />
</bean>
Doing that allowed me to replace custom implementation of authenticator with generic BindAuthenticator and then my Java search started working
I got the same error, couldn't find a solution.
Finally I changed the application pool identity to network service and everything worked like a charm.
(I have windows authentication and anonymous enabled on my site)

Resources