Spring Secuirty and Cas logging redirecting - spring

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.

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>

Fail to locate j_spring_security_check in Spring Security

I am working on spring Security, I am facing the issue "Problem accessing /CustomRole/j_spring_security_check"
My web.xml file is as follow
<sec:http auto-config="true" disable-url-rewriting="true"
use-expressions="true">
<!-- When access is refused, will go to the 403.jsp -->
<sec:intercept-url pattern="/login.jsp" filters="none" />
<sec:form-login login-page="/login.jsp"
authentication-failure-url="/login.jsp?error=true"
login-processing-url="/j_spring_security_check.action"
default-target-url="/index.jsp"
always-use-default-target="true" />
<sec:logout logout-success-url="/login.jsp" />
<sec:http-basic />
<!-- An increase in filter and Acegi, this is not the same, can not modify
the default filter, the filter is located in the FILTER_SECURITY_INTERCEPTOR
before> -->
<sec:custom-filter before="FILTER_SECURITY_INTERCEPTOR"
ref="myFilter" />
</sec:http>
<!-- A custom filter, you must include the authenticationManager, accessDecisionManager,
securityMetadataSource three attributes, All control we will achieve in the
three class, explain the specific configuration, see> -->
<beans:bean id="myFilter"
class="com.demo.security.MyFilterSecurityInterceptor">
<beans:property name="authenticationManager" ref="authenticationManager" />
<beans:property name="accessDecisionManager" ref="myAccessDecisionManagerBean" />
<beans:property name="securityMetadataSource" ref="securityMetadataSource" />
</beans:bean>
<!-- The authentication manager, entrance for user authentication, which
implements the UserDetailsService interface can be -->
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="myUserDetailService">
<!-- If the user's password using encryption, you can add a little salt
"" <password-encoder hash="md5"/> -->
</authentication-provider>
</authentication-manager>
<beans:bean id="myUserDetailService" class="com.demo.security.MyUserDetailService" />
<!-- Access decision device, determines whether a user has a role, that
you have sufficient permissions to access a resource -->
<beans:bean id="myAccessDecisionManagerBean" class="com.demo.security.MyAccessDecisionManager">
</beans:bean>
<!-- Resource source data definition, the definition of a resource can be
what role access -->
<beans:bean id="securityMetadataSource"
class="com.demo.security.MyInvocationSecurityMetadataSource" />
After hitting the launch page it open login page successfully.But when i provide login credential and try to hit login it fails and throw error related to "j_spring_security_check"
I have created code as per the available on http://www.programering.com/a/MTNygjMwATY.html

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

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

Resources