Invoke Spring security with RestTemplate - spring

I am new to spring security and I am confused over how spring security works. I have a filter chain defined as follows:
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/rest/internal/*</url-pattern>
<url-pattern>/user/*</url-pattern>
<url-pattern>/http/*</url-pattern>
</filter-mapping>
and my security config looks as follows:
<global-method-security pre-post-annotations="enabled"/>
<http entry-point-ref="aligneUnauthorisedEntryPoint" use-expressions="true" create-session="never">
<!--<intercept-url pattern="/user/login" access="isAuthenticated()"/>-->
<intercept-url pattern="/rest/internal/**" access="isAuthenticated()"/>
<intercept-url pattern="/http/**" access="isAuthenticated()"/>
<custom-filter ref="loginFilter" position="FORM_LOGIN_FILTER"/>
<custom-filter ref="logoutFilter" position="LOGOUT_FILTER"/>
<csrf disabled="true"/>
<http-basic/>
</http>
<authentication-manager alias="aligneAuthenticationManager">
<authentication-provider ref="aligneUserAuthenticationProvider"/>
</authentication-manager>
<beans:bean id="loginFilter" class="com.altra.middleware.security.AligneAuthenticationFilter">
<beans:property name="authenticationManager" ref="aligneAuthenticationManager"/>
<beans:property name="authenticationFailureHandler" ref="aligneAuthenticationFailureHandler"/>
<beans:property name="authenticationSuccessHandler" ref="aligneAuthenticationSuccessHandler"/>
<beans:property name="filterProcessesUrl" value="/user/login"/>
</beans:bean>
When i am hitting the following URL from my browser:
http://localhost:9099/jedi/rest/internal/main/dropdown
I get the following error.
Secondly, same exception comes occurs when i try to invoke the service from another spring controller using RestTemplate.
HTTP ERROR 503 Problem accessing /jedi/rest/internal/main/dropdown.
Reason:
Full authentication is required to access this resource
where /jedi is the application context.
If i comment out <intercept-url pattern="/rest/internal/**" access="isAuthenticated()"/> then the correct controller's method is called.
What is the significance of access="isAuthenticated()" ? We have this method overridden but it never gets called.
How should i go about this problem ?

Related

Using DB authentication and SAML authentication with Spring Security

I have an application that is used by two sets of users-internal users for the the company and external customers. My application will communicate either DB and LDAP or DB and SAML. The users can be differentiated based on the username stored in database.
I have to perform authentication based on configuration set. I am succeeded with DB and LDAP, But i am not able to run application with DB and SAML. The application is to be built using Spring Security 3.1.x.
application-context.xml
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/login" access="isAuthenticated()" />
<form-login login-page="/index" default-target-url="/login"
authentication-failure-handler-ref="customAuthenticationFailureHandler"
authentication-success-handler-ref="customAuthenticationSuccessHandler"/>
<logout invalidate-session="true" logout-url="/logout"/>
<session-management invalid-session-url="/welcome"></session-management>
</http>
application-database.xml
<beans:bean id="jdbcDaoImplService"
class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">
<beans:property name="usersByUsernameQuery" value="SELECT USER_ID, USER_PASSWORD,'true' enabled FROM USERS WHERE EXTERNAL_USER='D' AND USER_ID=?"/>
<beans:property name="authoritiesByUsernameQuery" value="select u.user_id, r.ROLE_NAME ROLE_NAME from USERS u, USER_ASSIGNED_ROLES ua, SECURITY_ROLES r
where u.user_id = ua.user_id
and ua.role_id = r.role_id
and r.ROLE_ID in(select ROLE_ID from USER_ASSIGNED_ROLES where USER_ID=?)"/>
<beans:property name="dataSource" ref="myDataSource" />
</beans:bean>
<beans:bean id="jdbcProvider" class="com.configurations.helper.CustomDBAuthenticationProvider">
<beans:constructor-arg ref = "jdbcDaoImplService"/>
<beans:property name="passwordEncoder" ref="passwordEncoder" />
</beans:bean>
application-saml.xml
<security:http pattern="/saml/web/**" use-expressions="false">
<security:access-denied-handler error-page="/saml/web/metadata/login"/>
<security:form-login login-processing-url="/saml/web/login" login-page="/saml/web/metadata/login" default-target-url="/saml/web/metadata"/>
<security:intercept-url pattern="/saml/web/metadata/login" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<security:intercept-url pattern="/saml/web/**" access="ROLE_ADMIN"/>
<security:custom-filter before="FIRST" ref="metadataGeneratorFilter"/>
</security:http>
<security:http entry-point-ref="samlEntryPoint" use-expressions="false">
<security:intercept-url pattern="/**" access="IS_AUTHENTICATED_FULLY"/>
<security:custom-filter before="FIRST" ref="metadataGeneratorFilter"/>
<security:custom-filter after="BASIC_AUTH_FILTER" ref="samlFilter"/>
</security:http>
<bean id="samlAuthenticationProvider" class="org.springframework.security.saml.SAMLAuthenticationProvider">
</bean>
authentication-providers.xml
<authentication-manager alias="authenticationManager">
<authentication-provider ref="jdbcProvider" />
<authentication-provider ref="samlAuthenticationProvider" />
</authentication-manager>
With above configuration i am getting Filter already configured exception.
Below is the exception after starting application:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.filterChainProxy':
Invocation of init method failed; nested exception is java.lang.IllegalArgumentException:
A universal match pattern ('/**') is defined before other patterns in the filter chain, causing them to be ignored.
Please check the ordering in your <security:http> namespace or FilterChainProxy bean configuration

How to implement ResourceUrlEncodingFilter with spring security

I am working on application which is using spring 3.2.3.RELEASE and Spring Security 3.1.4.RELEASE. I want to implement static resource versioning in my application. I did implement this functionality with spring 4.3.11 with this reference http://www.baeldung.com/cachable-static-assets-with-spring-mvc i.e, working fine. Now when I am going to implement this with my old application i.e, not working.I am providing you the code snippet
In my web.xml
<filter>
<filter-name>resourceUrlEncodingFilter</filter-name>
<filter-class>
org.springframework.web.servlet.resource.ResourceUrlEncodingFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>resourceUrlEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
In spring.xml
<security:http auto-config="true" pattern="/**" use-expressions="true">
<!-- Login pages -->
<security:form-login login-page="/login"
default-target-url="/home/"
login-processing-url="/j_spring_security_check"
authentication-failure-url="/login?error" />
<security:logout logout-success-url="/home/"/>
<!-- Security zones -->
<security:intercept-url pattern="/favicon.ico" access="hasRole(ROLE_ANONYMOUS)" />
<security:intercept-url pattern="/login" access="permitAll"/>
<security:intercept-url pattern="/resources/**" access="permitAll"/>
<security:intercept-url pattern="/admin/**" access="hasRole('ROLE_SUPER_USER')" />
<security:intercept-url pattern="/**" access="isAuthenticated()" />
</security:http>
We are also using the caching filter in dispatcher servlet
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/resources/**" />
<bean id="responseCachingFilter" class="org.springframework.web.servlet.mvc.WebContentInterceptor">
<property name="cacheSeconds" value="0" />
<property name="useExpiresHeader" value="true" />
<property name="cacheMappings">
<props>
<prop key="/resources/**">21600</prop>
</props>
</property>
</bean>
</mvc:interceptors>
</mvc:interceptor>
and the versioning code
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/")
.setCacheControl(CacheControl.maxAge(6, TimeUnit.HOURS))
.resourceChain(false)
.addResolver(new VersionResourceResolver().addContentVersionStrategy("/**"))
.addTransformer(new CssLinkResourceTransformer());
}
but my versioning code is not working. Please suggest me where I need to change the code or other approach need to implement.
Thanks In advance

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>

Use of custom authenticationManager and daoAuthenticationProvider beans

i am running small spring mvc 3 application (Spitter from spring in action 3 book ) which is downloaded from github . In spring security file they have written beans for authenticationManager and daoAuthenticationProvider like this
<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.3.xsd">
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/home*" access="hasAnyRole('ROLE_USER','ROLE_ADMIN')"/>
<intercept-url pattern="/spitters/**" access="hasAnyRole('ROLE_USER','ROLE_ADMIN')" />
<intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" />
<form-login login-processing-url="/static/j_spring_security_check"
login-page="/login" authentication-failure-url="/login?login_error=t" />
<logout logout-success-url="/home"/>
</http>
<beans:bean id="daoAuthenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<beans:property name="userDetailsService" ref="userDetailsService" />
</beans:bean>
<beans:bean id="authenticationManager"
class="org.springframework.security.authentication.ProviderManager">
<beans:property name="providers">
<beans:list>
<beans:ref local="daoAuthenticationProvider" />
</beans:list>
</beans:property>
</beans:bean>
<authentication-manager>
<authentication-provider user-service-ref="userDetailsService">
<password-encoder hash="md5" />
</authentication-provider>
</authentication-manager>
or this link https://github.com/karolgornicki/spitter/blob/master/src/main/webapp/WEB-INF/spring-security.xml
What is the use of these two beans authenticationManager and daoAuthenticationProvider . After commenting also this application works perfectly .
I think the AuthenticationManager delegates the fetching of persistent user information to one or more AuthenticationProviders. The authentication-providers (DaoAuthenticationProvider, JaasAuthenticationProvider, LdapAuthenticationProvider, OpenIDAuthenticationProvider for example) specialize in accessing specific user-info repositories. Something else is mentioned in this part of the reference manual. It says:
You may want to register additional AuthenticationProvider beans with the ProviderManager and you can do this using the element with the ref attribute, where the value of the attribute is the name of the provider bean you want to add.
In other words, you can specify multiple AuthenticationProviders, for example one that looks for users in an LDAP database and another that looks in an SQL database.

Application Controllers getting called before custom RememberMeAuthenticationFilter

We are trying to implement Spring security in our application. We are extending RememberMeAuthenticationFilter. But trouble is that our application Controllers are getting called before RememberMeAuthenticationFilter. Is there anyway to force RememberMeAuthenticationFilter to be called before application Controllers?
Below are my configuaations. In debug mode I could see that FilterChainProxy.VirtualFilterChain has two sets of filters - original filters and additional filters. Original filters has springSecurityFilterChain but it doesn't call custom RememberMeAuthenticationFilter. And additional filters has RememberMeAuthenticationFilter. Controller is getting called via DispatcherServlet at the end of original filters.
Web.xml
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
spring-security-context.xml
<http use-expressions="true" auto-config="false" entry-point-ref="authenticationProcessingFilterEntryPoint" create-session="ifRequired" >
<long list of intercept-url here>
<intercept-url pattern="/**" access="permitAll" requires-channel="any"/>
<custom-filter ref="rememberMeProcessingFilter" position="REMEMBER_ME_FILTER" />
<custom-filter ref="authenticationProcessingFilter" position="FORM_LOGIN_FILTER" />
</http>
<beans:bean id="rememberMeProcessingFilter" class="uk.co.and.dealofday.security.SecurityRememberMeAuthenticationFilter">
<beans:property name="authenticationManager" ref="authenticationManager" />
<beans:property name="rememberMeServices" ref="rememberMeServices" />
</beans:bean>
<beans:bean id="authenticationProcessingFilter" class="uk.co.and.dealofday.security.SecurityUsernamePasswordAuthenticationFilter">
<beans:property name="authenticationManager" ref="authenticationManager" />
<beans:property name="rememberMeServices" ref="rememberMeServices" />
<beans:property name="userService" ref="userService"/>
<beans:property name="securityHelper" ref="securityHelper" />
</beans:bean>
declare custom remember filter after custom authentication filter
<custom-filter ref="authenticationProcessingFilter" position="FORM_LOGIN_FILTER" />
<custom-filter ref="rememberMeProcessingFilter" position="REMEMBER_ME_FILTER" />

Resources