Spring Security 3.2.3 RELEASE with JavaConfig - spring-security

I have a Spring Security configured in XML that works just fine. Now, I'm trying to have it expressed in JavaConfig only so as to get rid of the XML configuration altogether.
I've looked at the reference documentation, and at many blogs and support requests, but I still cannot find the solution.
It gives me the following exception:
Could not autowire field: private org.springframework.security.web.FilterChainProxy
com.thalasoft.learnintouch.rest.config.WebTestConfiguration.springSecurityFilterChain;
Pitifully I resorted to post my own request here...
The code:
#Configuration
#ComponentScan(basePackages = { "com.thalasoft.learnintouch.rest" })
public class WebTestConfiguration {
#Autowired
private WebApplicationContext webApplicationContext;
#Autowired
private FilterChainProxy springSecurityFilterChain;
}
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}
public class WebInit implements WebApplicationInitializer {
private static Logger logger = LoggerFactory.getLogger(WebInit.class);
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
registerListener(servletContext);
registerDispatcherServlet(servletContext);
registerJspServlet(servletContext);
}
private void registerListener(ServletContext servletContext) {
// Create the root application context
AnnotationConfigWebApplicationContext appContext = createContext(ApplicationConfiguration.class, WebSecurityConfiguration.class);
// Set the application display name
appContext.setDisplayName("LearnInTouch");
// Create the Spring Container shared by all servlets and filters
servletContext.addListener(new ContextLoaderListener(appContext));
}
private void registerDispatcherServlet(ServletContext servletContext) {
AnnotationConfigWebApplicationContext webApplicationContext = createContext(WebConfiguration.class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(webApplicationContext));
dispatcher.setLoadOnStartup(1);
Set<String> mappingConflicts = dispatcher.addMapping("/");
if (!mappingConflicts.isEmpty()) {
for (String mappingConflict : mappingConflicts) {
logger.error("Mapping conflict: " + mappingConflict);
}
throw new IllegalStateException(
"The servlet cannot be mapped to '/'");
}
}
private void registerJspServlet(ServletContext servletContext) {
}
private AnnotationConfigWebApplicationContext createContext(final Class... modules) {
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(modules);
return appContext;
}
}
#Configuration
#EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
CustomAuthenticationProvider customAuthenticationProvider;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthenticationProvider);
}
#Bean
public DelegatingFilterProxy springSecurityFilterChain() {
DelegatingFilterProxy filterProxy = new DelegatingFilterProxy();
return filterProxy;
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").hasRole("ROLE_ADMIN").and().httpBasic();
http.authorizeRequests().antMatchers("/admin/login", "/admin/logout", "/admin/denied").permitAll()
.antMatchers("/admin/**").hasRole("ROLE_ADMIN")
.and()
.formLogin()
.loginPage("/admin/login")
.defaultSuccessUrl("/admin/list")
.failureUrl("/admin/denied?failed=true")
.and()
.rememberMe();
http.logout().logoutUrl("/admin/logout").logoutSuccessUrl("/admin/login").deleteCookies("JSESSIONID");
}
}
The XML configuration that I hope to get rid of:
<!-- A REST authentication -->
<http use-expressions="true" pattern="/admin/**">
<intercept-url pattern="/**" access="hasRole('ROLE_ADMIN')" />
<http-basic entry-point-ref="restAuthenticationEntryPoint" />
<logout />
</http>
<!-- A form based browser authentication -->
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/admin/login" access="permitAll" />
<intercept-url pattern="/admin/logout" access="permitAll" />
<intercept-url pattern="/admin/denied" access="permitAll" />
<intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" />
<form-login
login-page="/admin/login"
default-target-url="/admin/list"
authentication-failure-url="/admin/denied?failed=true"
always-use-default-target="true" />
<logout logout-success-url="/admin/login" />
<logout delete-cookies="JSESSIONID" />
</http>
<!-- A custom authentication provider on legacy data -->
<authentication-manager>
<authentication-provider ref="customAuthenticationProvider" />
</authentication-manager>
UPDATE:
I added a Configuration directive:
#Configuration
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}
and an explicit import directive:
#Import({ SecurityWebApplicationInitializer.class })
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
}
But the exception remained the exact same.
I'm running Spring Security 3.2.4.RELEASE and Spring 3.2.9.RELEASE
If you have any suggestion, it is welcomed.

I removed this bean definition from the security configuration and it seems to have solved the issue
#Bean
public DelegatingFilterProxy springSecurityFilterChain() {
DelegatingFilterProxy filterProxy = new DelegatingFilterProxy();
return filterProxy;
}

Related

Ways to toggle spring security SAML on and off

I have a pretty standard implementation of spring security saml into my application in addition to other authentication mechanisms. Out of the box SAML will not be configured but can be configured through a form, so by default SAML should be disabled. I'd like to easily be able to toggle SAML on / off but am not sure what the best way to do this would be.
It seems like one approach would be to do a custom FilterChainProxy where if I check if saml is enabled and if so to ignore the samlFilter chain(How to delete one filter from default filter stack in Spring Security?) and also do a similar implementation for the Metadata Generator Filter.
Any advice would be great.
Here is my config:
<http auto-config="false" use-expressions="true"
access-decision-manager-ref="webAccessDecisionManager"
disable-url-rewriting="false"
create-session="never"
authentication-manager-ref="authenticationManager">
<custom-filter before="FIRST" ref="metadataGeneratorFilter"/>
<custom-filter after="BASIC_AUTH_FILTER" ref="samlFilter"/>
</http>
Metadata Generator Filter:
<beans:bean id="metadataGeneratorFilter" class="org.springframework.security.saml.metadata.MetadataGeneratorFilter">
<beans:constructor-arg>
<beans:bean class="org.springframework.security.saml.metadata.MetadataGenerator">
<beans:property name="entityId" value="${saml.entityId}"/>
<beans:property name="signMetadata" value="${saml.signMetadata}"/>
</beans:bean>
</beans:constructor-arg>
</beans:bean>
Saml Filter:
<beans:bean id="samlFilter" class="org.springframework.security.web.FilterChainProxy">
<filter-chain-map request-matcher="ant">
<filter-chain pattern="/saml/login/**" filters="samlEntryPoint"/>
<filter-chain pattern="/saml/logout/**" filters="samlLogoutFilter"/>
<filter-chain pattern="/saml/metadata/**" filters="metadataDisplayFilter"/>
<filter-chain pattern="/saml/SSO/**" filters="samlWebSSOProcessingFilter"/>
<filter-chain pattern="/saml/SSOHoK/**" filters="samlWebSSOHoKProcessingFilter"/>
<filter-chain pattern="/saml/SingleLogout/**" filters="samlLogoutProcessingFilter"/>
<filter-chain pattern="/saml/discovery/**" filters="samlIDPDiscovery"/>
</filter-chain-map>
</beans:bean>
EDIT: Here is my implementation, it is a bit hackish and relies on a deprecated method but it works
The below snippet disables MetadataGeneratorFilter:
public class MyMetadataGeneratorFilter extends MetadataGeneratorFilter {
private boolean isActive = false;
public MyMetadataGeneratorFilter(MetadataGenerator generator) {
super(generator);
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (isActive) {
processMetadataInitialization((HttpServletRequest) request);
}
chain.doFilter(request, response);
}
public void setActive(boolean active) {
isActive = active;
}
}
There is also the samlFilter / FilterChainMap which is autowired. If saml is enabled, I leave this chain as is, if it is disabled, I set the chain to an empty map in my service which enables / disables saml.
Upon initialization, I get the filterchainmap values:
private Map<RequestMatcher, List<Filter>> map;
#Override
public void init() throws ServiceException, MetadataProviderException {
SamlConfig samlConfig = getConfig();
map = samlFilter.getFilterChainMap();
applySamlConfig(samlConfig);
}
In the below method, I set the filter chain map to either the original map provided in the spring xml(if enabled) or an empty map (if disabled).
public void applySamlConfig(SamlConfig samlConfig) throws ServiceException, MetadataProviderException {
if (!samlConfig.isEnabled()) {
Map<RequestMatcher, List<Filter>> emptyMap = samlFilter.getFilterChainMap();
emptyMap.clear();
samlFilter.setFilterChainMap(emptyMap);
return;
}
samlFilter.setFilterChainMap(map);
i added a custom filter in the entry-point-ref definition. This filter skips all following filters if the feature is not enabled.
<security:http entry-point-ref="samlEntryPoint">
<security:intercept-url pattern="/**" access="IS_AUTHENTICATED_FULLY" />
<!-- This filter checks if the SSO-Feature is enabled - otherwise all following security filters will be skipped -->
<security:custom-filter before="BASIC_AUTH_FILTER" ref="ssoEnabledFilter"/>
<security:custom-filter before="FIRST" ref="metadataGeneratorFilter" />
<security:custom-filter after="BASIC_AUTH_FILTER" ref="samlFilter" />
The ssoEnabledFilter:
public class SsoEnabledFilter extends GenericFilterBean {
#Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain filterChain) throws IOException, ServletException {
boolean ssoEnabled = isSsoEnabled();
if (ssoEnabled) {
filterChain.doFilter(request, response);
} else {
request.getRequestDispatcher(((HttpServletRequest) request).getServletPath()).forward(request, response);
}
}
}
So far I've been implementing this using a custom Spring namespace which includes or skips certain beans based on the backend configuration and reloading of the Spring context in case the backend configuration changes.
Edit : fixed error signaled by TheTurkish
If you want to be able to switch the use of SAML on a running application, the simpler would be to use a wrapper around samlFilter. For example
public class FilterWrapper extends GenericFilterBean {
private Filter inner;
private boolean active;
private boolean targetFilterLifeCycle = false;
public Filter getInner() {
return inner;
}
public void setInner(Filter inner) {
this.inner = inner;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
#Override
public void doFilter(ServletRequest sr, ServletResponse sr1, FilterChain fc) throws IOException, ServletException {
if (active) {
inner.doFilter(sr, sr1, fc);
}
else {
fc.doFilter(str,sr1);
}
}
#Override
protected void initFilterBean() throws ServletException {
super.initFilterBean();
if (inner == null) {
throw new ServletException("Inner cannot be null");
}
if (targetFilterLifeCycle) {
inner.init(getFilterConfig());
}
}
#Override
public void destroy() {
super.destroy();
if (inner != null && targetFilterLifeCycle) {
inner.destroy();
}
}
}
You can use it that way :
<bean id="samlFilter" class="...FilterWrapper" p:active="false">
<property name=inner>
<!-- the real samlFilter bean -->
<bean class="org.springframework.security.web.FilterChainProxy">
...
</bean>
</property>
</bean>
As it is a bean, you inject it where you want to activate/deactivate Saml and simple call :
samlFilter.setActive(active);

Spring Security "<authorize url='...'>" tag failed to evaluate url properly when there are multiple <http> elements

I'm trying to use spring security's "url" attribute of <authorize> tag. I got into a weird situation where the tag seems doesn't take effect.
My business need is to use two <http> elements, one for web service access and another for normal user access: the web service access is stateless but the user access is session based, that is why we need two http elements.
To illustrate this problem, I will use the spring security 3.1.4 tutorial instead. I can reproduce this problem by only adding one extra <http> element to the spring config file.
The original applicationContext-secutiry.xml from tutorial is defined like this:
<http pattern="/static/**" security="none"/>
<http pattern="/loggedout.jsp" security="none"/>
<http use-expressions="true">
<intercept-url pattern="/secure/extreme/**" access="hasRole('supervisor')"/>
<intercept-url pattern="/secure/**" access="isAuthenticated()" />
....
</http>
It's landing page, index.jsp, uses "authorize" tag like this:
<sec:authorize url='/secure/index.jsp'>
<p>
You can currently access "/secure" URLs.
</p>
</sec:authorize>
When a user first time tries to access this page, the tag will check the permission to url '/secure/index.jsp', which requires authentication and thus, the tag will NOT displace its content and UI display message like.
Your principal object is....: null
Now, change applicationContext-security.xml by adding a new http element before the last "http" element
<http pattern="/static/**" security="none"/>
<http pattern="/loggedout.jsp" security="none"/>
<!--This is the new element added-->
<http pattern="/user/**"
use-expressions="true">
<intercept-url pattern="/user/**" access="hasRole('user')"/>
<http-basic />
</http>
<http use-expressions="true">
<intercept-url pattern="/secure/extreme/**" access="hasRole('supervisor')"/>
<intercept-url pattern="/secure/**" access="isAuthenticated()" />
....
</http>
Now, I access the index.jsp (no login yet) and the page actually prints out a message saying:
Your principal object is....: null
You can currently access "/secure" URLs.
You can currently access "/secure/extreme" URLs.
The "authorize" tag evaluates to true in this case, even if I haven't logged in!
I tried to debug through source code, DefaultFilterInvocationSecurityMetadataSource, and found that when the first http request, "/index.jsp" comes in, it uses the default element (the last one) in applicationContext-security.xml but when the "" tag tries to check access to "/secure/index.jsp", DefaultFilterInvocationSecurityMetadataSource is using the new element and its getAttributes() return null to DefaultWebInvocationPrivilegeEvaluator which eventually return true.
This looks like a spring security bug to me: the authorize tag url, "/secure/index.jsp" should match the default "http", not the other one.
One workaround I used is to copy the "intercept-url" definitions for "/secure/index.jsp" and "/secure/extreme/index.jsp" from the default "http" to the new "http" element and then the UI works as expected. But I don't want to copy codes!
Any idea is appreciated.
I have resolved this issue as following.
Java:
package com.github.kazuki43zoo.web.security;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.access.WebInvocationPrivilegeEvaluator;
import org.springframework.stereotype.Component;
#Component
public class CustomWebInvocationPrivilegeEvaluatorProvideFilter implements Filter,
WebInvocationPrivilegeEvaluator, BeanPostProcessor {
private List<WebInvocationPrivilegeEvaluator> webInvocationPrivilegeEvaluators = new ArrayList<>();
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
request.setAttribute(WebAttributes.WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE, this);
chain.doFilter(request, response);
}
#Override
public void destroy() {
webInvocationPrivilegeEvaluators.clear();
}
#Override
public boolean isAllowed(String uri, Authentication authentication) {
for (WebInvocationPrivilegeEvaluator privilegeEvaluator : webInvocationPrivilegeEvaluators) {
if (!privilegeEvaluator.isAllowed(uri, authentication)) {
return false;
}
}
return true;
}
#Override
public boolean isAllowed(String contextPath, String uri, String method,
Authentication authentication) {
for (WebInvocationPrivilegeEvaluator privilegeEvaluator : webInvocationPrivilegeEvaluators) {
if (!privilegeEvaluator.isAllowed(contextPath, uri, method, authentication)) {
return false;
}
}
return true;
}
#Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
return bean;
}
#Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
if (bean instanceof WebInvocationPrivilegeEvaluator
&& !bean.getClass().isAssignableFrom(getClass())) {
webInvocationPrivilegeEvaluators.add((WebInvocationPrivilegeEvaluator) bean);
}
return bean;
}
}
web.xml:
<filter>
<filter-name>CustomWebInvocationPrivilegeEvaluatorProvideFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetBeanName</param-name>
<param-value>customWebInvocationPrivilegeEvaluatorProvideFilter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CustomWebInvocationPrivilegeEvaluatorProvideFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Here is what worked for me:
org.springframework.context.ApplicationContext ctx = org.springframework.web.context.support.WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
java.util.Map<String, org.springframework.security.web.access.WebInvocationPrivilegeEvaluator>
wipes = ctx.getBeansOfType(org.springframework.security.web.access.WebInvocationPrivilegeEvaluator.class);
if(wipes.size() > 0){
//I need last one
org.springframework.security.web.access.WebInvocationPrivilegeEvaluator appEvaluator =
(WebInvocationPrivilegeEvaluator)wipes.values().toArray()[wipes.size() - 1];
//set request attribute so that JSP tag can use it request.setAttribute(org.springframework.security.web.WebAttributes.WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE
, appEvaluator);
}

PreAuthentication with Spring Security -> Based on URL parameters

The customer want to have the following scenario:
Customer hands out link (webapp address) with 2 parameters to the webapp user. Based on these variables the user will take on specific roles in the webapp.
I don't want any authorization in it. There should only be the authentication check which looks at these url parameters and checks if they are valid and will connect the user to the appropriate role.
How can I realize this?! Is there already a solution available?
Thanks!
regards Matthias
I already solved the problem.
For those who are interested ....
web.xml
<!-- ===== SPRING CONFIG ===== -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<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>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
/WEB-INF/applicationContext-security.xml
</param-value>
</context-param>
applicationContext.xml
<context:component-scan base-package="at.beko.rainstar2" />
<tx:annotation-driven transaction-manager="transactionManager" />
applicationContext-security.xml
<!-- Configuring security not finished!! -->
<http create-session="never" use-expressions="true" auto-config="false"
entry-point-ref="preAuthenticatedProcessingFilterEntryPoint">
<intercept-url pattern="/authError.xhtml" access="permitAll" />
<intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
<custom-filter position="PRE_AUTH_FILTER" ref="preAuthFilter" />
<session-management session-fixation-protection="none" />
</http>
<beans:bean id="userDetailsServiceImpl"
class="at.beko.rainstar2.service.impl.UserDetailsServiceImpl" />
<beans:bean id="preAuthenticatedProcessingFilterEntryPoint"
class="at.beko.rainstar2.model.LinkForbiddenEntryPoint" />
<beans:bean id="preAuthenticationProvider"
class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
<beans:property name="preAuthenticatedUserDetailsService"
ref="userDetailsServiceImpl" />
</beans:bean>
<beans:bean id="preAuthFilter"
class="at.beko.rainstar2.service.filter.UrlParametersAuthenticationFilter">
<beans:property name="authenticationManager" ref="appControlAuthenticationManager" />
</beans:bean>
<authentication-manager alias="appControlAuthenticationManager">
<authentication-provider ref="preAuthenticationProvider" />
</authentication-manager>
LinkForbiddenEntryPoint.java
public class LinkForbiddenEntryPoint implements AuthenticationEntryPoint {
#Override
public void commence(HttpServletRequest request,
HttpServletResponse response, AuthenticationException authException)
throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.sendRedirect("/rainstar2-webapp/authError.xhtml");
}
}
UrlParametersAuthenticationFilter.java
public class UrlParametersAuthenticationFilter extends
AbstractPreAuthenticatedProcessingFilter {
#Override
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
if (request.getParameterMap().size() == 2) {
return true;
}
return false;
}
#Override
protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
String[] credentials = new String[2];
credentials[0] = request.getParameter("param1");
credentials[1] = request.getParameter("param2");
return credentials;
}
}
UserDetailsServiceImpl.java
#SuppressWarnings("deprecation")
public class UserDetailsServiceImpl implements
AuthenticationUserDetailsService<Authentication> {
#Override
public UserDetails loadUserDetails(Authentication token)
throws UsernameNotFoundException {
UserDetails userDetails = null;
String[] credentials = (String[]) token.getPrincipal();
boolean principal = Boolean.valueOf(token.getCredentials().toString());
if (credentials != null && principal == true) {
String name = credentials[0];
if ("admin".equalsIgnoreCase(name)) {
userDetails = getAdminUser(name);
} else if ("händler".equalsIgnoreCase(name)) {
userDetails = getRetailerUser(name);
} else if ("user".equalsIgnoreCase(name)) {
userDetails = getUserUser(name);
}
}
if (userDetails == null) {
throw new UsernameNotFoundException("Could not load user : "
+ token.getName());
}
return userDetails;
}
private UserDetails getAdminUser(String username) {
Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
grantedAuthorities.add(new GrantedAuthorityImpl("ROLE_USER"));
grantedAuthorities.add(new GrantedAuthorityImpl("ROLE_RETAILER"));
grantedAuthorities.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
return new User(username, "notused", true, true, true, true,
grantedAuthorities);
}
private UserDetails getRetailerUser(String username) {
Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
grantedAuthorities.add(new GrantedAuthorityImpl("ROLE_USER"));
grantedAuthorities.add(new GrantedAuthorityImpl("ROLE_RETAILER"));
return new User(username, "notused", true, true, true, true,
grantedAuthorities);
}
private UserDetails getUserUser(String username) {
Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
grantedAuthorities.add(new GrantedAuthorityImpl("ROLE_USER"));
return new User(username, "notused", true, true, true, true,
grantedAuthorities);
}
}
The way I have resolved this with similar situations is to to use a servlet filter to grab the parameters. I would recommend extending the org.springframework.web.filter.GenericFilterBean.
From these parameters, create an auth object of some sort (such as a token), that can be passed into the AuthenticationManager which you can autowire in (or get in some other method).
You will then need to have an AuthenticationProvider that can handle your auth object and generate a UserDetails object with the GrantedAuthority collection you need to satisfy the specific roles you want the user to have.

Custom PasswordEncoder

I need to create a custom password encoder. I have completed to following tasks :
applicationContext-Security.xml
<authentication-manager alias="authenticationManager">
<authentication-provider>
<password-encoder ref="AppPasswordEncoder" />
<jdbc-user-service data-source-ref="dataSource" authorities-by-username-query="select username,password from username where username=?"/>
</authentication-provider>
<beans:bean class="com.app.security.MyPasswordEncoder" id="AppPasswordEncoder"/>
</authentication-manager>
class
public class SnatiPasswordEncoder implements PasswordEncoder {
#Override
public String encodePassword(String arg0, Object arg1)
throws DataAccessException {
return null;
}
#Override
public boolean isPasswordValid(String arg0, String arg1, Object arg2)
throws DataAccessException {
return false;
}
}
Several steps to encode the password :
ISO-8859-1
md5
base64
What should be my next step ?

JSF 2.0 + Spring Security 2.x

I using JSF 2.0 + Icefaces 2.0 and try to implement spring security 2.06 (not 3.x due to compatible problems with Icefaces 2.0).
I follow this guide (I think it is for JSF 1.x and Icefaces 1.8):
http://facestutorials.icefaces.org/tutorial/spring-security-basic.html
But I have problem to integrate the spring framework. I have added these lines to web.xml:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring Security -->
<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>
Then I have a file, applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-2.0.2.xsd">
<security:http auto-config="true" access-denied-page="/pages/accessDenied.xhtml">
<security:intercept-url pattern="/secured/**" access="ROLE_ALLACCESS, ROLE_URLACCESS"/>
<security:form-login login-page="/pages/springSecurityLogin.xhtml"
default-target-url="/secured/welcome.xhtml"/>
<security:logout logout-success-url="/pages/logoutSuccess.xhtml"/>
</security:http>
<security:authentication-provider user-service-ref="userDetailsService"/>
<bean id="userDetailsService" class="security.UserDetailsServiceImpl">
<constructor-arg ref="userRepository"/>
</bean>
<bean id="userRepository" class="security.UserDaoImpl"/>
</beans>
The userDetailsService class is implemented according to:
package security;
import org.springframework.dao.DataAccessException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;
public class UserDetailsServiceImpl implements UserDetailsService {
private UserDAO userDAO;
public UserDetailsServiceImpl(UserDAO userDAO) {
this.userDAO = userDAO;
}
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
AppUser user = userDAO.findUser(username);
if (user == null)
throw new UsernameNotFoundException("User not found: " + username);
else {
return makeUser(user);
}
}
private org.springframework.security.userdetails.User makeUser(AppUser user) {
return new org.springframework.security.userdetails.User(user.getLogin(), user
.getPassword(), true, true, true, true,
makeGrantedAuthorities(user));
}
private GrantedAuthority[] makeGrantedAuthorities(AppUser user) {
GrantedAuthority[] result = new GrantedAuthority[user.getRoles().size()];
int i = 0;
for (String role : user.getRoles()) {
result[i++] = new GrantedAuthorityImpl(role);
}
return result;
}
}
I also has a login bean:
package web.bean.security;
import org.springframework.security.ui.AbstractProcessingFilter;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
#ManagedBean(name="login")
public class Login {
// properties
private String userId;
private String password;
/**
* default empty constructor
*/
public Login() {
Exception ex = (Exception) FacesContext
.getCurrentInstance()
.getExternalContext()
.getSessionMap()
.get(AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY);
if (ex != null)
FacesContext.getCurrentInstance().addMessage(
null,
new FacesMessage(FacesMessage.SEVERITY_ERROR, ex
.getMessage(), ex.getMessage()));
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void login(ActionEvent e) throws java.io.IOException {
FacesContext.getCurrentInstance().getExternalContext().redirect("/spring-authentication/j_spring_security_check?j_username=" + userId + "&j_password=" + password);
}
}
The problem is when I running a jsf file which using the login bean:
The requested resource () is not available.
I'm using Tomcat 7.
Can you please help me?
Best Regards /kungcc
I think you need to add the webapplication name before the /j_spring_security_check
like /WebAppName/j_spring_security_check that will aply the spring on all what comes after /webAppName
Does omitting /spring-authentication in the login() method of login bean help?
public void login(ActionEvent e) throws java.io.IOException {
FacesContext.getCurrentInstance().getExternalContext().redirect("/j_spring_security_check?j_username=" + userId + "&j_password=" + password);
}

Resources