Spring security remember me not working, getting SecurityContex tHolder not populated with remember-me token - spring

i have below code to enable remember me authentication in configuration xml
<remember-me services-ref="rememberMeServices" key="testKeyForBlog" />
<beans:bean id="rememberMeServices" class="com.ringee.web.login.security.controller.CustomTokenBasedRememberMeServices">
<beans:constructor-arg name="key" value="testKeyForBlog"/>
<beans:constructor-arg name="manageUserServiceImpl" ref="manageUserServiceImpl" />
<beans:constructor-arg name="tokenRepository" ref="managePersistentTokenServiceImpl" />
</beans:bean>
i have implemented AbstractRememberMeServices to have custom remember me authentication.
when i enter my login id and password with remember me check box enabled, RememberMeAuthenticationFilter filter is invoked, but below line
SecurityContextHolder.getContext().getAuthentication() == null
where authentication object is not null, which eventually make remember me service not invoked, after running in debug mode , i see below debug message
DEBUG [org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter] (http--127.0.0.1-8080-6) SecurityContex
tHolder not populated with remember-me token, as it already contained: 'com.ringee.web.login.security.controller.CustomUserAuthentication#6ee367b0'
my application doesnt has form login, instead does ajax login, hence i have customized. i have custom entry point.
<http pattern="/**" entry-point-ref="customEntryPoint">
<custom-filter ref="ajaxTimeoutRedirectFilter" after="EXCEPTION_TRANSLATION_FILTER" />
<remember-me services-ref="rememberMeServices" key="testKeyForBlog" />
<custom-filter position="PRE_AUTH_FILTER" ref="ringeeFilter" />
<intercept-url pattern="/index.jsp" access="ROLE_ANONYMOUS" />
<intercept-url pattern="/menu/registration" access="ROLE_ANONYMOUS" />
<custom-filter ref="logOutFilter" position="LOGOUT_FILTER" />
<access-denied-handler ref="accessDeniedHandler" />
</http>
when login with remember me check box enable.. no cookie is been set because remember service is not getting invoked, since it authentication object has present already. dont know what is wrong with my configuration, thanks for you answers

Related

spring security session times out

I am using spring security 4.1, the issue that i face is when i try to login i am sent back to the session expired page several times. I have tried multiple things like adding my own HttpSessionListener also by adding
org.springframework.security.web.session.HttpSessionEventPublisher
but the session keeps expiring. I read in one of the questions the explanation for such behavior
"It's possible for Spring Security to invalidate session in some cases (for example, after logging in, the user gets a new HttpSession)."
I used Fiddler tool to see what is happening, i see user is authenticated but is redirected to session expired page instantly. I want to allow same user to login as many times as he wants. I also read in some places that it will help to move to spring 3.x but i assume it might be for cases when older version of spring was used.
please suggest. Thank You
<http auto-config="true" use-expressions="true"
authentication-manager-ref="authenticationManager">
<session-management
invalid-session-url="/login?eventType=sessionTimedOut"
session-fixation-protection="none"
/>
<intercept-url pattern="/login" access="permitAll" />
<intercept-url pattern="/*" access="hasAnyAuthority('FF_USER','FF_ADMIN')" />
<form-login login-page="/login"
authentication-success-handler-ref="authenticationSuccessHandler"
authentication-failure-handler-ref="customAuthenticationFailureHandler"
login-processing-url="/j_spring_security_check"
username-parameter="j_username"
password-parameter="j_password"
/>
<logout invalidate-session="false" logout-success-url="/login?eventType=logout"
logout-url="/j_spring_security_logout" delete-cookies="JSESSIONID"/>
<csrf token-repository-ref="csrfTokenRepository" />
</http>
<beans:bean id="csrfTokenRepository"
class="org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository">
<beans:property name="headerName" value="X-XSRF-TOKEN" />
</beans:bean>
<beans:bean id="authenticationSuccessHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<beans:property name="defaultTargetUrl" value="/home"/>
<beans:property name="alwaysUseDefaultTargetUrl" value="true"/>
</beans:bean>
<beans:bean id="customAuthenticationFailureHandler" class="*.*.CustomAuthenticationFailureHandler">
<beans:property name="defaultFailureUrl" value="/login?eventType=error"></beans:property>
<beans:property name="baseFailureUrl" value="/login?eventType=error"></beans:property>
</beans:bean>
<beans:bean id="authenticationManager"
class="org.springframework.security.authentication.ProviderManager">
<beans:constructor-arg>
<beans:list>
<beans:ref bean="ldapAuthenticationProvider" />
</beans:list>
</beans:constructor-arg>
<beans:property name="eraseCredentialsAfterAuthentication"
value="true" />
</beans:bean>
<http>
<logout delete-cookies="JSESSIONID" />
</http>
Unfortunately this can't be guaranteed to work with every servlet container, so you will need to test it in your environment[8].
So you need to add a customer logout handler that implements LogoutHandler to LogoutFilter handlers.
<http auto-config="true" use-expressions="true" authentication-manager-ref="authenticationManager">
...
<custom-filter ref="logoutFilter" position="LOGOUT_FILTER" />
...
</http>
<bean id="logoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
<constructor-arg name="logoutSuccessUrl" value="/login?eventType=logout" />
<!-- implement LogoutHandler, Websphere log out -->
<constructor-arg name="handlers" ref="{customer logout }" />
<property name="filterProcessesUrl" value="/j_spring_security_logout" />
</bean>

Spring Security logins fail when migrating Spring mvc projects to Spring boot

I migrated a working Spring mvc project to Spring boot. Refer to Section 81.3 of this document and this question. Modules are working properly, but SpringSecurity can not login.
In the open when the home page will jump to the login page, and then log in after the home page and login page repeatedly redirects are 302 HTTP response, and then an error ERR_TOO_MANY_REDIRECTS.
After debugging, when I log on Custom UserDetailsService can correctly find and return UserDetails, custom SimpleUrlAuthenticationSuccessHandler also called onAuthenticationSuccess normally, but in the filter chain in a call FilterSecurityInterceptor this filter, SpringSecurity login status is cleared, I And does not call logout of the HTTP request.
I carefully check that in the set create-session = "stateless" clear the login status is normal, but it seems that my application can not be properly re-authorized. After the request has been SecurityContextHolder.getContext().GetAuthentication().GetPrincipal() has been anonymousUesr (Cookies correctly passed loginKey = b3668242-574a-498e-bd03-243e28dc805c; SESSIONID_HAP = 98963370-8561-40a2-9898-a5e80f7d1186).
This project is more complex, the following is an important part of the configuration and code, and their role is basically the original and the equivalent.
SpringBootConfigure.java SpringBoot enter point.
#SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
#ImportResource({"classpath:/spring/applicationContext*.xml","classpath:/spring/appServlet/servlet*.xml"})
public class SpringBootConfigure {
...
}
spring security xml config
<http access-decision-manager-ref="accessDecisionManager">
<csrf disabled="true"/>
<intercept-url pattern="/login" access="permitAll" />
<intercept-url pattern="/login.html" access="permitAll" />
<intercept-url pattern="/verifiCode" access="permitAll" />
<intercept-url pattern="/common/**" access="permitAll" />
<intercept-url pattern="/boot/**" access="permitAll" />
<intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
<access-denied-handler error-page="/403.html"/>
<form-login login-page='/login' authentication-success-handler-ref="successHandler"
authentication-failure-handler-ref="loginFailureHandler"/>
<custom-filter ref="captchaVerifierFilter" before="FORM_LOGIN_FILTER"/>
<logout logout-url="/logout"/>
<headers defaults-disabled="true">
<cache-control/>
</headers>
</http>
<beans:bean id="loginFailureHandler" class="com.hand.hap.security.LoginFailureHandler"/>
<beans:bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased">
<beans:constructor-arg>
<beans:list>
<beans:bean class="org.springframework.security.web.access.expression.WebExpressionVoter"/>
</beans:list>
</beans:constructor-arg>
</beans:bean>
<authentication-manager>
<authentication-provider user-service-ref="customUserDetailsService">
<password-encoder ref="passwordManager"/>
</authentication-provider>
</authentication-manager>
<beans:bean id="captchaVerifierFilter" class="com.hand.hap.security.CaptchaVerifierFilter">
<beans:property name="captchaField" value="verifiCode"/>
</beans:bean>
<beans:bean id="successHandler" class="com.hand.hap.security.CustomAuthenticationSuccessHandler">
<beans:property name="defaultTargetUrl" value="/index"/>
</beans:bean>

Spring Security Pre-Authentication / Login

I did a proof of concept with Spring Security in order to perform pre authentication by using the PRE_AUTH_FILTER filter. It worked OK, but I'd like to know if I can redirect to the login page if the this filter does not work, because I get HTTP 403.
I mean, if the initial request does not contain the SM_USER field in the header, how can I redirect to the login page? I need to consider these two scenarios (when it contains the field - SM_USER -, and when not) and I was not able to get it working. Any ideas about it?
Pra-authentication works smoothly with login authentication in Spring Security. You just setup a working login form configuration, and add the PRE_AUTH_FILTER filter.
Spring only redirects to login page, if after passing the authentication filters, it detects that user is not authenticated when he should be. So if the request contains the expected field in header, the user will be authenticated by the PRE_AUTH_FILTER filter, and will not go to the login page. But if it does not contain one, Spring security will detect a lack of authentication and redirect to login page.
These are my settings:
<http auto-config="true" use-expressions="true" entry-point-ref="http403EntryPoint">
<intercept-url pattern="/login" access="permitAll" />
<intercept-url pattern="/logout" access="permitAll" />
<intercept-url pattern="/accessdenied" access="permitAll" />
<intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
<custom-filter before="PRE_AUTH_FILTER" ref="siteminderFilter" />
<form-login login-page="/login" default-target-url="/list" authentication-failure-url="/accessdenied" />
<logout logout-success-url="/logout" />
</http>
<beans:bean id="siteminderFilter" class="org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter">
<beans:property name="principalRequestHeader" value="SM_USER"/>
<beans:property name="authenticationManager" ref="authenticationManager" />
<beans:property name="exceptionIfHeaderMissing" value="false" />
</beans:bean>
<beans:bean id="preauthAuthProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
<beans:property name="preAuthenticatedUserDetailsService">
<beans:bean id="userDetailsServiceWrapper" class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
<beans:property name="userDetailsService" ref="customUserDetailsService"/>
</beans:bean>
</beans:property>
</beans:bean>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="employeeDAO" />
<authentication-provider ref="preauthAuthProvider" />
</authentication-manager>
<beans:bean id="customUserDetailsService" class="com.test.security.CustomUserDetailsService"></beans:bean>
<beans:bean id="http403EntryPoint" class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint"></beans:bean>

Spring Secuirty and Cas logging redirecting

I have a strange problem. I make my casAuthenticationFilter with an authenticationSuccessHandler. Everything works fine. Look my code:
<beans:bean id="casAuthenticationFilter" class="org.springframework.security.cas.web.CasAuthenticationFilter" >
<beans:property name="authenticationManager" ref="authenticationManager" />
<!-- Propiedad aƱadida para el redireccionamiento a AMS1.1 -->
<beans:property name="authenticationSuccessHandler">
<beans:bean class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<beans:property name="defaultTargetUrl" value="http://192.168.1.32:8080/AMS1.1/"/>
</beans:bean>
</beans:property>
</beans:bean>
<http auto-config="true" use-expressions="true" access-denied-page="/forbidden.xhtml" entry-point-ref="casAuthEntryPoint">
<intercept-url pattern="/parameters.xhtml" access="hasRole('SES_ADMIN')" />
<intercept-url pattern="/*" access="hasRole('SES_USER')" />
<custom-filter ref="casAuthenticationFilter" position="CAS_FILTER" />
<!--<logout invalidate-session="true" logout-url="/logout" logout-success-url="/cas/logout"/>-->
<custom-filter ref="casSingleSignOutFilter" after="LOGOUT_FILTER"/>
</http>
But here is the catch. Whenever I Log In via localhost:8080/logingpage/ redirect me to http://192.168.1.32:8080/AMS1.1/. Thats what I want. But whenever I Log in via MyIp example 192.168.1.2/logingpage/ redirect me to page I enter. Example, wheneever I enter a page 192.168.1.2:8080/somepage redirects me to 192.168.2:8080/logingpage and when loging succes redirects me to 192.168.1.2:8080/somepage and that's what I don't want I want to redirect me to http://192.168.1.32:8080/AMS1.1/. But when I use localhost instead of my current Ip Everything works fine. Am I missing something?
My local ip is 192.168.1.32.
From SavedRequestAwareAuthenticationSuccessHandler API doc, you can achieve this by setting alwaysUseDefaultTargetUrl to true.
If the alwaysUseDefaultTargetUrl property is set to true, the defaultTargetUrl will be used for the destination. Any DefaultSavedRequest stored in the session will be removed.

Spring Security Authentication Issue

We need help with regard to Authentication using Spring Security. When we try to key in the login credentials for our application and click on submit, We are getting an invalid credentials error.
we have checked the database and the authentication details that we are using to login seems to be correct. But still getting the below exception
[DEBUG,LdapAuthenticationProvider,http-localhost%2F127.0.0.1-8080-1] Processing authentication request for user: admin
[DEBUG,FilterBasedLdapUserSearch,http-localhost%2F127.0.0.1-8080-1] Searching for user 'admin', with user search [ searchFilter: 'sAMAccountName={0}', searchBase: 'DC=ad,DC=infosys,DC=com', scope: subtree, searchTimeLimit: 0, derefLinkFlag: true ]
[INFO,SpringSecurityLdapTemplate,http-localhost%2F127.0.0.1-8080-1] Ignoring PartialResultException
[WARN,LoggerListener,http-localhost%2F127.0.0.1-8080-1] Authentication event AuthenticationFailureBadCredentialsEvent: admin; details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: DEC9042719AA53736897C4383DCF8FE8; exception: Bad credentials
[DEBUG,UsernamePasswordAuthenticationFilter,http-localhost%2F127.0.0.1-8080-1] Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials
Im trying to connect to the sqlserver2008 database and trying to login.Below is the security.xml file that we are using
<http auto-config='false' realm="MaskIT Realm" access-denied-page="/403.jsp">
<intercept-url pattern="/*.htm" access="ROLE_ADMIN,ROLE_REQUESTOR,ROLE_APPROVER" />
<intercept-url pattern="/login.jsp" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<form-login login-page="/login.jsp"
authentication-failure-url="/login.jsp?login_error=1"
default-target-url="/redirect.jsp" />
<http-basic />
<intercept-url pattern="/securityService" access="IS_AUTHENTICATED_ANONYMOUSLY"
requires-channel="http" />
<logout logout-success-url="/login.jsp" />
</http>
<b:bean id="myAuthenticationProvider"
class="com.infosys.setl.himi.maskit.security.SwitchingAuthenticationProvider">
<b:constructor-arg ref="paramManager" />
<b:property name="providers">
<b:list>
<b:ref local="daoAuthenticationProvider" />
<b:ref local="ldapProvider" />
</b:list>
</b:property>
</b:bean>
<b:bean id="daoAuthenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<b:property name="userDetailsService" ref="userDetailsService" />
<!-- <b:property name="passwordEncoder" ref="passwordEncoder" /> -->
</b:bean>
<b:bean id="userDetailsService"
class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">
<b:property name="dataSource" ref="dataSourceMSSQL" />
<b:property name="usersByUsernameQuery">
<b:value>SELECT user_id ,password,active FROM sec_users
WHERE
user_id=?</b:value>
</b:property>
<b:property name="authoritiesByUsernameQuery">
<b:value>SELECT a.user_id AS user_id,b.roleName AS roleName FROM
sec_users a, emaskit_roles b
WHERE a.roleID = b.roleID AND
a.user_id=?</b:value>
</b:property>
</b:bean>
I would like to know how & when the sql query is getting executed for checking the authentication. Is it calling any java class( so that i can debug the code and check where it is failing) to perform the check or is it done internally by the Spring framework.
Please Assist. Thanks in Advance
What brothers me is that you logfile shows that you try to use an Ldap for authentication (LdapAuthenticationProvider) but you xml file shows that you try to use a DaoAuthenticationProvider.
I really think you massed up you deployment, either you looked/deployed on the wrong server or you did not deployed the (actual version) application at all.
In addition there is a mistake in you configuration: you have to tell spring security to use your daoAuthenticationProvider:
add this:
<authentication-manager alias="authenticationManager">
<authentication-provider ref="daoAuthenticationProvider"/>
</authentication-manager>

Resources