/j_spring_security_check has no matching filters - primavera

I have two kingdoms security and each refferencio one AuthenticationManager different with authentication-manager-ref, also each specific http cabeceera the pattern = "/", but when I run and try to log into each Report form me get the error:
09.16.2014 17:03:25 DEBUG FilterChainProxy: 180 - / j_spring_security_check has not matching filters
09.16.2014 17:03:25 DEBUG DispatcherServlet: 819 - DispatcherServlet with name 'dispatcher' processing POST request for [/ testholding / j_spring_security_check]
09.16.2014 17:03:25 DEBUG RequestMappingHandlerMapping: 209 - Looking up handler method for path / j_spring_security_check
09.16.2014 17:03:25 DEBUG RequestMappingHandlerMapping: 219 - Did not find handler method for [/ j_spring_security_check]
09.16.2014 17:03:25 DEBUG SimpleUrlHandlerMapping: 169 - Matching patterns for request [/ j_spring_security_check] are [/ **]
09.16.2014 17:03:25 DEBUG SimpleUrlHandlerMapping: 193 - URI Template variables for request [/ j_spring_security_check] are {}
09.16.2014 17:03:25 DEBUG SimpleUrlHandlerMapping: 124 - Mapping [/ j_spring_security_check] to HandlerExecutionChain with handler [org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler#1477b3e] and 1 interceptor
09.16.2014 17:03:25 DEBUG DispatcherServlet: 957 - Null ModelAndView returned to DispatcherServlet with name 'dispatcher': Assuming HandlerAdapter completed request handling
09.16.2014 17:03:25 DEBUG DispatcherServlet: 913 - Successfully completed request
My spring-security.xml:
<!-- REINO DE SEGURIDAD USUARIO WEB SERVICE UNIVERSIA -->
<http auto-config="false"
use-expressions="true" pattern="/testUser/**" authentication-manager-ref="authenticationManager" >
<intercept-url pattern="/testUser/**" access="hasRole('ROLE_USER')" />
<intercept-url pattern="/j_spring_security_check" access="permitAll"/>
<access-denied-handler error-page="/403" />
<form-login login-page="/loginUser.html"
authentication-failure-url="/loginUser.html?login_error=true"
default-target-url="/testUser"
username-parameter="j_username" password-parameter="j_password" />
<!--<custom-filter position="FORM_LOGIN_FILTER" ref="userAuthenticationProcessingFilter" />-->
<logout invalidate-session="true" logout-success-url="/loginUser.html" />
</http>
<!--REINO DE SEGURIDAD ACCESO ADMINISTRADOR POR BASE DE DATOS -->
<http auto-config="true" use-expressions="true" pattern="/test/**" authentication-manager-ref="DBauthenticationManager">
<intercept-url pattern="/test/**" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/testUser/**" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/member/**" access="hasRole('ROLE_EMPLOYEES')" />
<access-denied-handler error-page="/403" />
<form-login login-page="/login.html"
authentication-failure-url="/login.html?login_error=true"
username-parameter="j_username" password-parameter="j_password" />
<logout invalidate-session="true" logout-success-url="/loginUser.html" />
</http>
<beans:bean id="md5PasswordEncoder"
class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" />
<beans:bean id="customUserDetailsService"
class="net.universia.test.autenticacionService.CustomUserDetailsService" />
<!-- Acceso contra base de datos -->
<authentication-manager alias="DBauthenticationManager" id="DBauthenticationManager">
<authentication-provider user-service-ref="customUserDetailsService">
<password-encoder hash="md5" />
</authentication-provider>
</authentication-manager>
<beans:bean id="customAuthenticationProvider"
class="net.universia.test.autenticacionService.CustomAuthenticationProvider" />
<!-- Acceso por WS -->
<authentication-manager id="authenticationManager" alias="authenticationManager">
<authentication-provider ref="customAuthenticationProvider" />
</authentication-manager>
My 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>
<dispatcher > ERROR </dispatcher >
<dispatcher > REQUEST </dispatcher >
<dispatcher > INCLUDE </dispatcher >
<dispatcher > FORWARD </dispatcher >
</filter-mapping>
Help me please!

Solve the problem
Just implement a /user/j_spring_security_check and /admin/ j_spring_security_check and call on login-processing-url="" and the action="" of each form jsp

Related

Spring Security always redirect to authentication-failure-url

recently i have use Spring Security for my Spring MVC Web Admin. I Have a trouble when using Spring Security. When login process, always redirect to authentication-failure-url. I have my own UserDetailsServiceImpl that implements UserDetailsService (from Spring Security Feature).
This is my spring security
<!-- enable use-expressions -->
<http auto-config="true">
<intercept-url pattern="/*" access="permitAll" />
<intercept-url pattern="/resources/**" access="permitAll" />
<intercept-url pattern="/error" access="permitAll" />
<intercept-url pattern="/**" access="isAuthenticated()" />
<!-- access denied page -->
<access-denied-handler error-page="/403" />
<form-login login-page="/" default-target-url="/index"
always-use-default-target="false" authentication-failure-url="/error"
login-processing-url="/j_spring_security_check" username-parameter="j_username"
password-parameter="j_password" />
<logout logout-success-url="/"
delete-cookies="JSESSIONID,SPRING_SECURITY_REMEMBER_ME_COOKIE"
logout-url="/j_spring_security_logout" invalidate-session="true" />
<!-- enable csrf protection -->
<!-- csrf /-->
</http>
<global-method-security pre-post-annotations="enabled" />
<beans:bean id="customAuthenticationSuccessHandler"
class="com.mezzo.security.AuthenticationSuccessListener">
</beans:bean>
<beans:bean id="myAuthenticationSuccessHandler"
class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<beans:property name="defaultTargetUrl" value="/index" />
<!-- After login, return to the last visited page -->
<beans:property name="useReferer" value="true" />
</beans:bean>
<beans:bean id="userDetailsService"
class="com.mezzo.security.UserDetailsServiceImpl" />
<authentication-manager>
<authentication-provider user-service-ref="userDetailsService">
<password-encoder hash="md5" />
</authentication-provider>
</authentication-manager>
Please, what's the problem with my security config xml.
Thanks in Advance. :)

Spring Security 4 - CredentialsExpiredException not redirecting to reset password - XML config

I am using Spring-Security 4 XML configuration to successfully implement password authentication in a spring-mvc webapp.
The problem I have is that when CredentialsExpiredException is thrown by DaoAuthenticationProvider, the system redirects to login-form, instead of reset password.
My context-security xml configuration is as follow:
<?xml version="1.0" encoding="UTF-8"?>
<b:beans xmlns="http://www.springframework.org/schema/security"
xmlns:b="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
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.xsd">
<b:bean id="authenticationEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<b:constructor-arg value="/index/form" />
</b:bean>
<http auto-config="true" use-expressions="true" disable-url-rewriting="true" entry-point-ref="authenticationEntryPoint" >
<intercept-url pattern="/" access="permitAll" requires-channel="https"/>
<intercept-url pattern="/index" access="permitAll" requires-channel="https"/>
<intercept-url pattern="/index/*" access="permitAll" requires-channel="https"/>
<intercept-url pattern="/**" access="hasAnyRole('USER','SYS_ADMIN' )" requires-channel="https"/>
<form-login
login-page="/index/form"
default-target-url="/dashboard"
login-processing-url="/index"
username-parameter="username"
password-parameter="password"
authentication-failure-handler-ref="exceptionTranslationFilter"
always-use-default-target="true"/>
<logout logout-url="/logout" logout-success-url="/index/logout"/>
<session-management>
<concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
</session-management>
</http>
<!-- password expiry functionality starts -->
<b:bean id="exceptionTranslationFilter" class="org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler">
<b:property name="exceptionMappings">
<b:props>
<b:prop key="org.springframework.security.authentication.CredentialsExpiredException">/resetpassword</b:prop>
</b:props>
</b:property>
<b:property name="defaultFailureUrl" value="/index/error"/>
</b:bean>
<b:bean id="authenticationManager" class="org.springframework.security.authentication.ProviderManager">
<b:constructor-arg name="providers">
<b:list>
<b:ref bean="daoAuthenticationProvider"/>
</b:list>
</b:constructor-arg>
</b:bean>
<b:bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider ">
<b:property name="userDetailsService" ref="customUserDetailsService" />
<b:property name="passwordEncoder" ref="passwordEncoder" />
</b:bean>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="customUserDetailsService" />
<authentication-provider ref="daoAuthenticationProvider" />
</authentication-manager>
<b:bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" >
</b:bean>
Given the above configuration, when I enter correct username and password of user whose credentials have expired, I get redirected to url = "/index/form"
I have ran the debugger (I'm using Eclipse), and the code execution is as follows (all classes belong to Spring Security 4):
AbstractUserDetailsAuthenticationProvider.authenticate() throws CredentialsExpiredException when executing postAuthenticationChecks.check(user);
ExceptionMappingAuthenticationFailureHandler.onAuthenticationFailure() gets the url to be /resetpassword before calling getRedirectStrategy().sendRedirect(request, response, url);
DefaultRedirectStrategy.sendRedirect() gets the redirect url to be "/myapp/resetpassword"
The problem occurs on LoginUrlAuthenticationEntryPoint.commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException).
Because useForward is set to false, it calls redirectUrl = buildRedirectUrlToLoginPage(request, response, authException);
redirectUrl ends up being "/index/form".
Even if I set useForward to true and subclass LoginUrlAuthenticationEntryPoint in order to override determineUrlToUseForThisRequest the AuthenticationException I get is of type InsufficientAuthenticationException.
The interesting thing is that the url on my browser is https://localhost:8443/myapp/resetpassword, but what it displays is the login form.
Have you encountered this problem before? If so, how did you get spring to redirect to reset password?
Most of the configuration I obtained from https://stackoverflow.com/a/14383194/158499
Thanks in advance, Lucas
<intercept-url pattern="/**" access="hasAnyRole('USER','SYS_ADMIN' )" requires-channel="https"/>
when redirect to /resetpassword will redirect to login page. Please allow this url to access without authentication.
<intercept-url pattern="/resetpassword" access="permitAll" requires-channel="https"/>

How to disable CSRF in Spring Security 4 only for specific URL pattern through XML configuration?

How to disable CSRF in Spring Security 4 only for specific URL pattern through XML configuration?
Spring-security.xml
<security:http auto-config="true" use-expressions="true" pattern="/ext/**">
<csrf disabled="true" />
</security:http>
<security:http auto-config="true" use-expressions="true" authentication-manager-ref="authenticationManager">
<security:intercept-url pattern="/auth/**" access="hasAnyRole('ROLE_USER')" />
<security:form-login login-page="/login" authentication-success-handler-ref="loginSuccessHandler" authentication-failure-url="/login" login-processing-url="/j_spring_security_check" />
<security:logout invalidate-session="true" logout-url="/logout" success-handler-ref="logoutSuccessHandler" />
</security:http>
My code works fine if I use only one security:http block, but after I add another block it throws error as below:
Error
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter gov.in.controller.filter.LoginAdtAuthFailHdlr.usernamePasswordAuthenticationFilter; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter] is defined: expected single matching bean but found 2: org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0,org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#1
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 58 more
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter] is defined: expected single matching bean but found 2: org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0,org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#1
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 60 more
Could not achieve with just XML changes. Below worked for me
Change in Spring-security.xml
<security:http use-expressions="true" authentication-manager-ref="authenticationManager">
<security:intercept-url pattern="/auth/**" access="hasAnyRole('ROLE_USER')" />
<security:form-login login-page="/login" authentication-success-handler-ref="loginSuccessHandler" authentication-failure-url="/login" login-processing-url="/j_spring_security_check" />
<security:logout invalidate-session="true" logout-url="/logout" success-handler-ref="logoutSuccessHandler" />
<security:csrf request-matcher-ref="csrfSecurityRequestMatcher" />
</security:http>
CsrfSecurityRequestMatcher
public class CsrfSecurityRequestMatcher implements RequestMatcher {
private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
private RegexRequestMatcher unprotectedMatcher = new RegexRequestMatcher("/ext/**", null);
#Override
public boolean matches(HttpServletRequest request) {
if(allowedMethods.matcher(request.getMethod()).matches()){
return false;
}
return !unprotectedMatcher.matches(request);
}
}
You can have two (or more) filter chains:
<http pattern="/your-specific/**">
<!-- ... -->
<csrf disabled="true"/>
</http>
<http>
<!-- ... -->
</http>

Restrict the access of REST URL's in browser

How to restrict the access of REST urls in browser, can any one please guide me what are the necessary changes to made in security.xml. My web app runs on spring MVC framework.
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p"
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.xsd">
<http pattern="/images/**" security="none" />
<http pattern="/styles/**" security="none" />
<http pattern="/scripts/**" security="none" />
<http pattern="/assets/**" security="none" />
<http auto-config="true">
<intercept-url pattern="/app/admin/**" access="ROLE_ADMIN" />
<intercept-url pattern="/app/passwordHint*" access="ROLE_ANONYMOUS,ROLE_ADMIN,ROLE_USER" />
<intercept-url pattern="/app/requestRecoveryToken*" access="ROLE_ANONYMOUS,ROLE_ADMIN,ROLE_USER, ROLE_PHYSICIAN, ROLE_PRACTICE_STAFF" />
<intercept-url pattern="/app/updatePassword*" access="ROLE_ANONYMOUS,ROLE_ADMIN,ROLE_USER, ROLE_PHYSICIAN, ROLE_PRACTICE_STAFF" />
<intercept-url pattern="/app/signup*" access="ROLE_ADMIN" />
<intercept-url pattern="/app/practice*" access="ROLE_ADMIN"/>
<!-- <intercept-url pattern="/app/patientReports*" access="ROLE_ADMIN"/> -->
<intercept-url pattern="/app/mediaFile/**" access="ROLE_ANONYMOUS"/>
<intercept-url pattern="/app/**" access="ROLE_ADMIN, ROLE_USER, ROLE_PHYSICIAN, ROLE_PRACTICE_STAFF" />
<form-login login-page="/login" authentication-failure-url="/login?error=true" login-processing-url="/j_security_check" />
<remember-me user-service-ref="userDao" key="e37f4b31-0c45-11dd-bd0b-0800200c9a66" />
</http>
<authentication-manager>
<authentication-provider user-service-ref="userDao">
<password-encoder ref="passwordEncoder">
</password-encoder>
</authentication-provider>
</authentication-manager>
<!-- Override the default password-encoder (BCrypt) by uncommenting the following and changing the class -->
<!-- <bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/> -->
<global-method-security>
<protect-pointcut expression="execution(* *..service.UserManager.getUsers(..))" access="ROLE_ADMIN" />
<protect-pointcut expression="execution(* *..service.UserManager.removeUser(..))" access="ROLE_ADMIN" />
</global-method-security>
Did you read the Spring security manual?
You need to restrict access to your rest URLs for certain roles. How you get those roles via the users depend on your setup.
For REST calls you probably don't want form login, but basic authentication.

Spring Android authentication with Spring Security

I have the following configuration in my security-context
<!-- web services-->
<http use-expressions="true" pattern="/services/**"
disable-url-rewriting="true" entry-point-ref="restAuthenticationEntryPoint">
<intercept-url pattern="/services/**" access="isFullyAuthenticated()"
requires-channel="https" />
<form-login authentication-success-handler-ref="restSuccessHandler"
authentication-failure-handler-ref="restAuthenticationFailureHandler" />
<logout invalidate-session="true" delete-cookies="JSESSIONID" />
</http>
<!-- browser -->
<http use-expressions="true"
disable-url-rewriting="true">
<intercept-url pattern="/signup*" access="permitAll"
requires-channel="https" />
<intercept-url pattern="/login*" access="permitAll"
requires-channel="https" />
<intercept-url pattern="/logout" access="permitAll"
requires-channel="https" />
<form-login authentication-success-handler-ref="myAuthenticationSuccessHandler"
login-page="/login" authentication-failure-url="/loginFailed" />
<intercept-url pattern="/**" access="isFullyAuthenticated()"
requires-channel="https" />
<session-management
session-authentication-error-url="/loginFailed">
<concurrency-control error-if-maximum-exceeded="true"
max-sessions="1" />
</session-management>
<logout invalidate-session="true" delete-cookies="JSESSIONID" />
</http>
and my springSecurityFilterChain is as
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
I am not able to perform login with
template.postForObject(targetURL + "services/j_spring_security_check", map,
String.class);
each time I tried it give me error as
POST request for "https://localhost:8443/someapp/services/j_spring_security_check" resulted in 401 (Unauthorized);
If I modify the url by removing services the error goes away. But I would like to differentiate between rest login (from mobile) and normal login (from browser). For rest login I'd like to return sessionID instead of redirecting to welcome page. What did I do wrong here ?
UPDATED
This is how I create the HTTP client:
System.setProperty("javax.net.ssl.trustStore", "d:/somekeystore");
System.setProperty("javax.net.ssl.trustStorePassword", "1234");
String targetURL = "https://localhost:8443/someapp/";
// configure HTTPClient and RestTemplate
HttpClient client = new HttpClient();
CommonsClientHttpRequestFactory commons = new CommonsClientHttpRequestFactory(
client);
RestTemplate template = new RestTemplate(commons);
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("j_username", "admin");
map.add("j_password", "1234");
map.add("rest", "true");
template.postForObject(targetURL + "services/j_spring_security_check", map,
String.class);
I'd guess it's cause you have the /services/** to require full authentication, but that's also the location to which you're trying to submit the login.
Try adding a login-page="services/login" and a "services/login" intercept-url with permitAll and use that as the login... ie:
<!-- web services-->
<http use-expressions="true" pattern="/services/**" disable-url-rewriting="true" entry-point-ref="restAuthenticationEntryPoint">
<intercept-url pattern="/services/login*" access="permitAll" requires-channel="https" />
<intercept-url pattern="/services/**" access="isFullyAuthenticated()" requires-channel="https" />
<form-login login-page="/services/login" authentication-success-handler-ref="restSuccessHandler" authentication-failure-handler-ref="restAuthenticationFailureHandler" />
<logout invalidate-session="true" delete-cookies="JSESSIONID" />
</http>
I have fixed the 401 (Unauthorized) error with specifying login-processing-url within <form-login> as
<form-login login-processing-url="/services/j_spring_security_check"
authentication-success-handler-ref="restSuccessHandler"
authentication-failure-handler-ref="restAuthenticationFailureHandler" />

Resources