LDAP with Spring - java

I want to use LDAP in my application in order to authenticate
I used in my previous config the database to authenticate
this is my previous config :
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/test/**" access="hasRole('ADMIN')" />
<intercept-url pattern="/test1/**" access="hasRole('USER')" />
<form-login login-page="/index.htm" authentication-success-handler-ref="authenticationSuccessRedirecthandler"
default-target-url = "/test/MainHealthCertificat.htm"
authentication-failure-url="/index.htm?error=1"/>
<logout logout-success-url="/index.htm" />
</http>
<beans:bean class="com..CustomAuthenticationHandler" id="authenticationSuccessRedirecthandler"></beans:bean>
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="select username, password, enabled from users where username=?"
authorities-by-username-query="select u.username, ur.authority from users u, user_roles ur where u.user_id = ur.user_id and u.username =? "
/>
</authentication-provider>
</authentication-manager>
</beans:beans>
this is my java class :
public class CustomAuthenticationHandler extends SimpleUrlAuthenticationSuccessHandler {
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
String adminTargetUrl = "/test/mypage.htm";
Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
if (roles.contains("ADMIN")) {
getRedirectStrategy().sendRedirect(request, response, adminTargetUrl);
}else {
super.onAuthenticationSuccess(request, response, authentication);
return;
}
}
}
No I want to use ldap to authenticate
I modified security-app-context.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/test/**" access="hasRole('ADMIN')" />
<intercept-url pattern="/test1/**" access="hasRole('USER')" />
<form-login login-page="/index.htm" authentication-success-handler-ref="authenticationSuccessRedirecthandler"
default-target-url = "/test/MainHealthCertificat.htm"
authentication-failure-url="/index.htm?error=1"/>
<logout logout-success-url="/index.htm" />
</http>
<beans:bean class="com..CustomAuthenticationHandler" id="authenticationSuccessRedirecthandler"></beans:bean>
<security:authentication-manager>
<security:ldap-authentication-provider
user-search-filter="(uid={0})"
user-search-base="ou=users"
group-search-filter="(uniqueMember={0})"
group-search-base="ou=groups"
group-role-attribute="cn"
role-prefix="ROLE_">
</security:ldap-authentication-provider>
</security:authentication-manager>
<security:ldap-server url="ldap://192.168.0.88:389" manager-dn="uid=admin,ou=system" manager-password="secret" />
</beans:beans>
but when I test I have this error :
Caused by: org.springframework.ldap.AuthenticationException: [LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db0
honestly I'm lost in settings ldap parameter : ou dc, cn,
I need help to configure the parameter of ldap in security-app-context.xml
this is a correct parameter of ldap which should be used in security-app-context.xml
Base Provider URL
ldap://192.168.0.88:389
Base DN
DC=MINISTER,DC=FR
Principal
CN=LDAP Requester,OU=Users,OU=Technical Accounts,OU=P9 Accounts,DC=MINISTER,DC=FR
Credentials
minister$9999
Users
Authentication Search Filter
(&(objectClass=person)(mail=#email_address#))
Import Search Filter
(objectClass=person)
User Mapping
Screen Name
sAMAccountName
Password
userPassword
Email Address
mail
Full Name
cn
First Name
givenName
Middle Name
middleName
Last Name
sn
Group
memberOf
Groups
Import Search Filter
(&(objectClass=group)(|(cn=MinisterUsers)(cn=MinisterAdministrateurs)(cn=Minister_*)))
Group Mapping
Group Name
cn
Description
sAMAccountName
User
member
Export
Users DN DC=MINISTER,DC=FR
Groups DN DC=MINISTER,DC=FR

Error code data 52e means invalid credentials supplied.
Please try to remove these attributes manager-dn="uid=admin,ou=system" manager-password="secret"
in the below.
<security:ldap-server url="ldap://192.168.0.88:389" manager-dn="uid=admin,ou=system" manager-password="secret" />
And give a try again. These are LDAP administration credentials and are not needed for the user authentication. User authentication are done using the values you supplied during login and spring by default try to Bind to LDAP using the provided details.
Also try to enable debug by including < debug /> tag in your security-app-context.xml and also add log4j.properties. This would give plenty of useful information for debuging.

Related

HTTP Status 403 - Access is denied Spring security

I've added Spring security to my project and configured it as
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd">
<http>
<intercept-url pattern="/add-job**" access="hasRole('USER')" />
<form-login
login-page="/login"
default-target-url="/"
always-use-default-target="true"/>
<logout />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="admin" password="admin" authorities="ROLE_ADMIN" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
through the above configuration when I go to /add-job it redirects me to \login and after login success I go to /add-job it shows me error
is there any mistake I've.
Spring security is right in denying access:
you define only one login in your authentication manager: admin/admin with one authority ROLE_ADMIN
you restrict access to /add-job** to users having ROLE_USER authority
No user can have the ROLE_USER authority, so spring security will always deny access.
You should use either ROLE_ADMIN or ROLE_USER (or any other ROLE_xxx you like) but use the same in protecting the resource (access="hasRole(xxx)") and granting to user (authorities="ROLE_xxx")
Anyway, the simplest way to fix is to add the required authority to user admin:
<user name="admin" password="admin" authorities="ROLE_ADMIN,ROLE_USER" />

Unauthorized BasicAuth Spring Security request after Oracle database restart

I have an application using BasicAuth with Spring Security. The credentials and roles are stored in a database.
For development I use MySQL, and production Oracle.
The problem happens, only in production with Oracle, when the database restarts while the application is running - I start receiving org.springframework.web.client.HttpClientErrorException: 401 Unauthorized.
This is my security context.
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<http auto-config='true'>
<intercept-url pattern="/v**/document/**" access="ROLE_DOCUMENT_USER" />
<intercept-url pattern="/v**/search/**" access="ROLE_DOCUMENT_USER" />
<http-basic/>
</http>
<authentication-manager>
<authentication-provider>
<password-encoder hash="sha-256">
<salt-source
system-wide="#{T(com.example.app.data.entity.RestUser).SALT}"/>
</password-encoder>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="select user_nm, password, enabled
from rest_usr_t where user_nm = ?"
authorities-by-username-query="select u.user_nm,
ur.authority from rest_usr_t u, rest_authority_t ur where
u.user_nm = ur.user_nm and u.user_nm = ?" />
</authentication-provider>
</authentication-manager>
<beans:bean id="restSecurityService"
class="com.example.app.security.rest.RestSecurityServiceImpl"/>
</beans:beans>
Any ideas what might be causing this, or ways to resolve it? Thanks, /w

How do I create a logout with Spring Security?

I am trying to find a way just to setup a URL that will logout my user from the system. this is only for testing. Right now we are using the default login page in spring secuirty
here is my spring-secuirty.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<global-method-security pre-post-annotations="enabled" />
<http use-expressions="true">
<intercept-url access="hasRole('ROLE_VERIFIED_MEMBER')" pattern="/ask-union**" />
<intercept-url access="hasRole('ROLE_VERIFIED_MEMBER')" pattern="/ask-welfare**" />
<intercept-url pattern='/*' access='permitAll' />
<form-login default-target-url="/ask-union" />
<logout logout-success-url="/" />
<session-management session-fixation-protection="newSession">
<concurrency-control max-sessions="1"/>
</session-management>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="xxxxx#aol.com.dev" password="testing" authorities="ROLE_VERIFIED_MEMBER" />
ser-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
Add this line to your config
<logout logout-url="/sign-out"/>
Then if you have a link to that URL, then it will sign you out
(Add it just below your logout success config)
I am a bit late on this. But answer may help others.
Use following code. logout-success-url is the URL you want take user after logging out.
<http auto-config="true" use-expressions="true" access-denied-page="/denied">
<logout invalidate-session="true" logout-success-url="/landing" delete-cookies="JSESSIONID" />
</http>
Double-check the URL you're using -- the absolute path should be your-domain/projectPath/sign-out, per SJS's example. If the relevant portion of your spring-security.xml file looks like the following, it should work:
<http use-expressions="true">
. . .
<logout
logout-success-url="/"
logout-url="/sign-out"/>
If you're able to authenticate, then simply browse to that path, and it should log you out. If it still doesn't try experimenting with the intermediary subdirectories specified in the URL, i.e. your-domain/projectPath/some-subdirectory/log-out.
Are you able to authenticate? It may not just be the logout aspect that's failing...
Late to the party, but for future reference -- if you are interested in seeing how the security filters are instantiated and configured from XML, take a look at the following package:
org.springframework.security.config.annotation.web.configurers
For the logout filter configuration, this will be the LogoutConfigurer class. If you review the LogoutConfigurer.createLogoutFilter() method, you'll see how the default Logout filter is created. This implies that you can do the following in an #Configuration class:
#Bean
public LogoutFilter logoutFilter() {
// NOTE: See org.springframework.security.config.annotation.web.configurers.LogoutConfigurer
// for details on setting up a LogoutFilter
SecurityContextLogoutHandler securityContextLogoutHandler = new SecurityContextLogoutHandler();
securityContextLogoutHandler.setInvalidateHttpSession(true);
LogoutFilter logoutFilter = new LogoutFilter("/", securityContextLogoutHandler);
logoutFilter.setLogoutRequestMatcher(new AntPathRequestMatcher("/logout"));
return logoutFilter;
}
If you have that, you can then either configure further by beans or have that bean picked up automatically since its method name is logoutFilter()

Want to login using spring security with Email OR mobile number

Want to login using Email OR mobile number using spring security.
Here is my code:--
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<http pattern="/admin" security="none" />
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/admin*" access="hasRole('SYS_ADMIN')" />
<intercept-url pattern="/cab-stop-admin*" access="hasAnyRole('SYS_ADMIN','CABSTOP_ADMIN')" />
<intercept-url pattern="/driver*" access="hasAnyRole('DRIVER','SYS_ADMIN','CABSTOP_ADMIN')" />
<intercept-url pattern="/customer*" access="hasAnyRole('CUSTOMER','SYS_ADMIN','CABSTOP_ADMIN')" />
<form-login login-page="/login" default-target-url="/role-check"
authentication-failure-url="/login?error=true" />
<remember-me key="_spring_security_remember_me" data-source-ref="fmsDataSource" authentication-success-handler-ref="loginSuccessHandler"/>
<logout logout-success-url="/" />
<access-denied-handler error-page="/login"/>
</http>
<beans:bean id="loginSuccessHandler" class="com.cabfms.authentication.LoginSuccessHandler"></beans:bean>
<authentication-manager>
<authentication-provider>
<!-- <password-encoder hash="md5" /> -->
<jdbc-user-service data-source-ref="fmsDataSource"
users-by-username-query="select Email,Password, 'true' as enabled from login_details where Is_Blocked = 'N' and Deleted='N' and Email=?"
authorities-by-username-query="select u.Email, ur.Role_Name from login_details u, role_master ur where u.Role_Master_Id = ur.Role_Master_Id and u.Email =?" />
</authentication-provider>
</authentication-manager>
</beans:beans>
In this code I have a query like
select Email,Password, 'true' as enabled from login_details where Is_Blocked = 'N' and Deleted='N' and Email=?
where I match only email but I want to match mobile number also.** means I want to match Email OR Mobile number (Any One) because I pass any one from tha JSP (Email OR Mobile)
So please Suggest your answer
Thanks In Advance
How does your JSP look like? Do you have a form with a j_username or are using two separate fields for email and mobile?
If you're passing both you'll have to implement your own authentication manager. The concrete user details service used by Spring Security when you declare jdbc-user-service> is a JdbcDaoImpl which implements UserDetailsService. That interface has a loadUserByUsername(String) method which obviously only accepts a username.
If you want to allow your users to enter either email or mobile in a single text input named j_username it might work if your query is
... where Is_Blocked = 'N' and Deleted='N' and (Email=? or Mobile=?)

Double authentication in GWT / EXT + Spring Security application

I have problems with double authentication. I have implemented the authentication form through pop-up window which is always on top. But I have problem probably with interceptors that cause the authentication request by Tomcat even before the start of application:
A username and password are being requested by http://127.0.0.1:8888.
The site says: "Spring Security Application"
If I disable interceptors, I see in log that SecurityContextHolder treats user as Anonymous.
So my question is:
Can I somehow disable that first Tomcat login screen?
My Spring-security configuration XML is:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd">
<authentication-manager alias="authenticationManager">
<authentication-provider ref="customAuthenticationProvider"/>
</authentication-manager>
<beans:bean id="customAuthenticationProvider" class="com.myCompany.model.security.CustomAuthenticationProvider" >
<beans:property name="databaseId" value="${configuration.databaseId}" />
<beans:property name="applicationId" value="${configuration.applicationId}" />
</beans:bean>
<http auto-config="true" >
<intercept-url pattern="/myApp/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<intercept-url pattern="/MyApp.html*" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<intercept-url pattern="/gwt/**" access="ROLE_USER"/>
<intercept-url pattern="/**/*.html" access="ROLE_USER"/>
<intercept-url pattern="/css/**" filters="none"/>
<intercept-url pattern="/**" access="ROLE_USER" />
<http-basic />
</http>
<global-method-security secured-annotations="enabled" />
</beans:beans>
In case I understand your question in a correct way you have a problem with double authentication e.g. a Tomcat authentication or an Apache Basic Auth and the Spring authentication mechanism.
While the last project I had related problems with an Apache Basic Auth and the Spring security mechanism. Before launch I had the task to "protect" the access to the site by an simple Apache Basic Auth. By enabling this in the Apache configuration Spring started to do the same: "Spring Security Application" has been shown all the time
The solution for this behaviour was to disable the auto-config:
<security:http auto-config="false" ...>
...
</security:http>
Your question is not too clear. You mention a Tomcat login screen, which I assume is the first screen of your web application, to allow a user to sign in.
If this is correct, and your login page is named, say login.html, all you have to do is configure the interceptors to allow anonymous access to this page-
<intercept-url pattern="/**/login.*" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<intercept-url pattern="/gwt/**" access="ROLE_USER"/>
<intercept-url pattern="/**/*.html" access="ROLE_USER"/>
<intercept-url pattern="/css/**" filters="none"/>
<intercept-url pattern="/**" access="ROLE_USER" />

Categories

Resources