Spring Security remember-me services - spring

I configured Spring Security with remember-me option.
<security:global-method-security secured-annotations="enabled" />
<security:http pattern="/login.html" security="none"/>
<security:http pattern="/signup.html" security="none"/>
<security:http pattern="/scripts/**" security="none"/>
<security:http pattern="/styles/**" security="none"/>
<security:http pattern="/images/**" security="none"/>
<security:http disable-url-rewriting="true" access-denied-page="/accessDenied.jsp">
<security:session-management>
<security:concurrency-control error-if-maximum-exceeded="false" max-sessions="10"/>
</security:session-management>
<security:form-login login-page="/login.html" login-processing-url="/login" authentication-failure-url="/login.html?login_error=1" default-target-url="/"/>
<security:intercept-url pattern='/**' access='ROLE_USER' />
<security:logout logout-url="/logout" logout-success-url="/"/>
<security:remember-me services-ref="rememberMeServices" />
</security:http>
and then the services itself:
<bean id="rememberMeServices" class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices">
<property name="tokenRepository" ref="myTokenRepository" />
<property name="userDetailsService" ref="userDetailsService" />
<property name="key" value="myRememberMeKey" />
<property name="alwaysRemember" value="true" />
</bean>
<bean id="myTokenRepository" class="com.mytwitter.web.security.MyTokenRepository">
</bean>
I can see in my schema that tokens are inserted/updated/deleted in database. so this is not an issue.
but sign on fails:
2012-02-13 13:35:56,497 DEBUG [http-bio-8080-exec-5] org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices - Remember-me cookie detected - 2065616
2012-02-13 13:35:56,498 DEBUG [http-bio-8080-exec-5] org.springframework.data.mongodb.core.MongoTemplate - findOne using query: { "series" : "Ww2a8WsycNlGWxZRDubTnA=="} in db.collection: mytwitter.rememberMeTokens - 2065617
2012-02-13 13:35:56,500 DEBUG [http-bio-8080-exec-5] org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.security.core.session.SessionRegistryImpl#0' - 2065619
2012-02-13 13:35:56,500 DEBUG [http-bio-8080-exec-5] org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices - Refreshing persistent login token for user 'aaaa', series 'Ww2a8WsycNlGWxZRDubTnA==' - 2065619
2012-02-13 13:35:56,510 DEBUG [http-bio-8080-exec-5] org.springframework.data.mongodb.core.MongoTemplate - calling update using query: { "series" : "Ww2a8WsycNlGWxZRDubTnA=="} and update: { "$set" : { "tokenValue" : "u0m7/ze3DpDInv27+JuPdQ==" , "date" : { "$date" : "2012-02-13T11:35:56.500Z"}}} in collection: rememberMeTokens - 2065629
2012-02-13 13:35:56,511 DEBUG [http-bio-8080-exec-5] org.springframework.data.mongodb.core.MongoTemplate - findOne using query: { "nickname" : "aaaa"} in db.collection: mytwitter.users - 2065630
2012-02-13 13:35:56,512 DEBUG [http-bio-8080-exec-5] org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices - Remember-me cookie accepted - 2065631
2012-02-13 13:35:56,512 DEBUG [http-bio-8080-exec-5] org.springframework.security.authentication.ProviderManager - Authentication attempt using org.springframework.security.authentication.RememberMeAuthenticationProvider - 2065631
2012-02-13 13:35:56,513 DEBUG [http-bio-8080-exec-5] org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.security.core.session.SessionRegistryImpl#0' - 2065632
2012-02-13 13:35:56,514 DEBUG [http-bio-8080-exec-5] org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter - SecurityContextHolder not populated with remember-me token, as AuthenticationManager rejected Authentication returned by RememberMeServices: 'org.springframework.security.authentication.RememberMeAuthenticationToken#5195b417: Principal: com.mytwitter.web.security.AuthUser#15880543; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_USER'; invalidating remember-me token - 2065633
org.springframework.security.authentication.BadCredentialsException: The presented RememberMeAuthenticationToken does not contain the expected key
at org.springframework.security.authentication.RememberMeAuthenticationProvider.authenticate(RememberMeAuthenticationProvider.java:64)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:102)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:182)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:125)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:173)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:964)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:679)
2012-02-13 13:35:56,529 DEBUG [http-bio-8080-exec-5] org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices - Interactive login attempt was unsuccessful. - 2065648
2012-02-13 13:35:56,529 DEBUG [http-bio-8080-exec-5] org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices - Cancelling cookie - 2065648
Actually what I do see as weird is that in line 2012-02-13 13:35:56,514 which prints Authentication object, SessionId is null. What am I missing?

The problem solved.
I should have add "key" property in remember-me parameter as well.
<security:remember-me services-ref="rememberMeServices" key="myRememberMeKey" />
and it should be the key with the same name as in "remeberMeServices" bean.

Related

Spring Security 4 Exception Access is denied

help me.I try to follow online.In The Screen 1, I used the username and password to login. but when i press to the login button then appears The Error Message [Exception error message Access is denied]
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/MH01*" access="permitAll" />
<intercept-url pattern="/resources/**" access="permitAll" />
<intercept-url pattern="/Erro" access="permitAll" />
<intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
<access-denied-handler error-page="/Erro"/>
<form-login
login-page="/MH01"
authentication-failure-url="/MH01?error"/>
<logout logout-url="/logout" logout-success-url="/MH01?logout" />
<csrf disabled="true"/>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query= "
SELECT USERNAME, PASSWORD, CASE ENABLED WHEN 1 THEN 'true' ELSE 'false' END 'ENABLED'
FROM TBL_USERS
WHERE USERNAME=?;"
authorities-by-username-query = "
SELECT USERNAME, PASSWORD, CASE ENABLED WHEN 1 THEN 'true' ELSE 'false' END 'ENABLED'
FROM TBL_USERS
WHERE USERNAME=?;"/>
</authentication-provider>
</authentication-manager>
Controller:
List<String> lsMessage = userService.doLogin(userDto);
if(!lsMessage.isEmpty()) {
userDto.setLsMessage(lsMessage);
} else {
SessionController.setDefaut(session);
return "redirect:/" + Common.VMH02;
}
return Common.VMH01;
Error:
2016-05-06 08:38:20 DEBUG FilterSecurityInterceptor:219 - Secure object: FilterInvocation: URL: /MH02; Attributes: [hasRole('ROLE_USER')]
2016-05-06 08:38:20 DEBUG FilterSecurityInterceptor:219 - Secure object: FilterInvocation: URL: /MH02; Attributes: [hasRole('ROLE_USER')]
2016-05-06 08:38:20 DEBUG FilterSecurityInterceptor:348 - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken#6fa90ed4: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#fffc7f0c: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 440EF5F23A36FF1A6DFACFD29BD8EF60; Granted Authorities: ROLE_ANONYMOUS
2016-05-06 08:38:20 DEBUG FilterSecurityInterceptor:348 - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken#6fa90ed4: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#fffc7f0c: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 440EF5F23A36FF1A6DFACFD29BD8EF60; Granted Authorities: ROLE_ANONYMOUS
2016-05-06 08:38:20 DEBUG AffirmativeBased:66 - Voter: org.springframework.security.web.access.expression.WebExpressionVoter#6ec34892, returned: -1
2016-05-06 08:38:20 DEBUG AffirmativeBased:66 - Voter: org.springframework.security.web.access.expression.WebExpressionVoter#6ec34892, returned: -1
2016-05-06 08:38:20 DEBUG ExceptionTranslationFilter:174 - Access is denied (user is anonymous); redirecting to authentication entry point
org.springframework.security.access.AccessDeniedException: Access is denied
at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84)
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:124)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
Login Form
<h3> Đăng nhập hệ thống</h3>
<table class="table-login">
<tr>
<td class="td-label"><label for="username">Tên đăng nhập</label></td>
<td><form:input type="text" path="username" id="userName" name ="userName"/></td>
</tr>
<tr>
<td class="td-label"><label for="password">Tên đăng nhập</label></td>
<td><form:password path="password" id="pass" /></td>
</tr>
</table>
<div class="btnSearch-div">
Đăng nhập
</div>

Spring LDAP Integration issue

I am trying to integrate spring security with ldap. Using spring core version 4.0.5, spring security version 3.2.2 and spring ldap version 1.3.2. Here is my security config xml
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<security:http auto-config="true" use-expressions="true">
<security:intercept-url pattern="/js/**"
access="true" />
<security:intercept-url pattern="/css/**"
access="true" />
<security:intercept-url pattern="/images/**"
access="true" />
<security:intercept-url pattern="/**"
access="hasRole('ROLE_USER')" />
</security:http>
<security:ldap-server id="ldapServer"
url="ldap://qadirectory.xxxx.com:389/" />
<security:authentication-manager alias="authenticationManager">
<security:ldap-authentication-provider
server-ref="ldapServer" user-dn-pattern="uid={0},ou=people,o=xxxx.com" />
</security:authentication-manager>
Getting following error while doing authentication thru default spring form
org.springframework.ldap.NameNotFoundException: [LDAP: error code 32 - No Such Object]; nested exception is javax.naming.NameNotFoundException: [LDAP: error code 32 - No Such Object]; remaining name ''
org.springframework.ldap.support.LdapUtils.convertLdapException(LdapUtils.java:174)
org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:305)
org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:258)
org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:605)
org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:523)
org.springframework.security.ldap.SpringSecurityLdapTemplate.searchForSingleAttributeValues(SpringSecurityLdapTemplate.java:171)
org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator.getGroupMembershipRoles(DefaultLdapAuthoritiesPopulator.java:215)
org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator.getGrantedAuthorities(DefaultLdapAuthoritiesPopulator.java:185)
org.springframework.security.ldap.authentication.LdapAuthenticationProvider.loadUserAuthorities(LdapAuthenticationProvider.java:197)
org.springframework.security.ldap.authentication.AbstractLdapAuthenticationProvider.authenticate(AbstractLdapAuthenticationProvider.java:82)
org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:177)
org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:211)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
root cause
javax.naming.NameNotFoundException: [LDAP: error code 32 - No Such Object]; remaining name ''
com.sun.jndi.ldap.LdapCtx.mapErrorCode(LdapCtx.java:3112)
com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:3033)
com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2840)
com.sun.jndi.ldap.LdapCtx.searchAux(LdapCtx.java:1849)
com.sun.jndi.ldap.LdapCtx.c_search(LdapCtx.java:1772)
com.sun.jndi.toolkit.ctx.ComponentDirContext.p_search(ComponentDirContext.java:386)
com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(PartialCompositeDirContext.java:356)
com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(PartialCompositeDirContext.java:339)
javax.naming.directory.InitialDirContext.search(InitialDirContext.java:267)
org.springframework.ldap.core.LdapTemplate$4.executeSearch(LdapTemplate.java:252)
org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:292)
org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:258)
org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:605)
org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:523)
org.springframework.security.ldap.SpringSecurityLdapTemplate.searchForSingleAttributeValues(SpringSecurityLdapTemplate.java:171)
org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator.getGroupMembershipRoles(DefaultLdapAuthoritiesPopulator.java:215)
org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator.getGrantedAuthorities(DefaultLdapAuthoritiesPopulator.java:185)
org.springframework.security.ldap.authentication.LdapAuthenticationProvider.loadUserAuthorities(LdapAuthenticationProvider.java:197)
org.springframework.security.ldap.authentication.AbstractLdapAuthenticationProvider.authenticate(AbstractLdapAuthenticationProvider.java:82)
org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:177)
org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:211)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
Your exception is thrown when Spring Security LDAP is trying to search for user groups. These groups are searched within LDAP base DN by default. Base DN is taken from the LDAP URL, for example:
<ldap-server url="ldap://springframework.org:389/dc=springframework,dc=org" />
In your case you don't specify base DN. You need to specify group search base manually:
<security:ldap-authentication-provider server-ref="ldapServer"
user-dn-pattern="uid={0},ou=people,o=xxxx.com"
group-search-base="ou=groups,o=xxxx.com" />

Spring Security redirect to Login Page after successful authentication by giving access denied exception

Facing strange problem : Application work fine on HTTP but redirects to login page again once we add SLL certificate :
Below is code snippet from spring-security.xml
<security:http auto-config="false" use-expressions="true" access-denied-page="/pages/denied.rs" entry-point-ref="authenticationEntryPoint" disable-url-rewriting="true">
<security:intercept-url pattern="/pages/doLogin.rs" requires-channel="any" access="hasAnyRole('ROLE_SYSTEM_ADMINISTRATOR', 'ROLE_KEY_ACCOUNT_MANAGER', 'ROLE_A', 'ROLE_B'" />
<security:intercept-url pattern="/**" requires-channel="any" access="hasAnyRole('ROLE_SYSTEM_ADMINISTRATOR', 'ROLE_KEY_ACCOUNT_MANAGER', 'ROLE_A', 'ROLE_B')"/>
<security:logout invalidate-session="true" logout-success-url="/pages/login.rs"/>
<security:custom-filter after="FILTER_SECURITY_INTERCEPTOR" ref="applicationRequestFilter" />
<security:custom-filter ref="authenticationFilter" position="FORM_LOGIN_FILTER" />
<security:custom-filter ref="concurrencyFilter" position="CONCURRENT_SESSION_FILTER"/>
<security:session-management session-authentication-strategy-ref="sas" invalid-session-url="/pages/sessiontimeout.rs"/>
</security:http>
<bean id="authenticationFilter"
class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter"
p:authenticationManager-ref="customAuthenticationManager"
p:authenticationFailureHandler-ref="customAuthenticationFailureHandler"
p:authenticationSuccessHandler-ref="customAuthenticationSuccessHandler" />
<bean id="customAuthenticationSuccessHandler"
class="com.mycomapny.CustomAuthenticationSuccessHandler"
p:defaultTargetUrl="/pages/doLogin.rs" />
<bean id="authenticationEntryPoint"
class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint"
p:loginFormUrl="/pages/login.rs" />
I have added SSL certificate in by JBOSS in standalone.xml as below:
<subsystem xmlns="urn:jboss:domain:web:1.4" default-virtual-server="default-host" native="false">
<connector name="http" protocol="HTTP/1.1" socket-binding="http" scheme="http" redirect-port="8443"/>
<connector name="https" protocol="HTTP/1.1" socket-binding="https" scheme="https" enable-lookups="false" secure="true">
<ssl name="selfsigned" password="password" certificate-key-file="D:\keystore.jks" protocol="TLSv1" verify-client="false"/>
</connector>
<virtual-server name="default-host" enable-welcome-root="true">
<alias name="127.0.0.1"/>
<alias name="example.com"/>
</virtual-server>
<configuration>
<jsp-configuration development="true"/>
</configuration>
</subsystem>
When I tries to access my application using HTTPS URL like https://mydomain.com:8443/mywebapp/login.rs , it displays the user name password page.
After entering valid credentials, it goes to authentication manger and before redirecting to success handler URL /doLogin.rs, it give below exception and redirects again to login page :
15:31:57,674 DEBUG [org.springframework.security.web.util.AntPathRequestMatcher] () Checking match of request : '/pages/dologin.
rs'; against '/pages/dologin.rs'
15:31:57,675 DEBUG [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] () Secure object: FilterInvocat
ion: URL: /pages/doLogin.rs; Attributes: [hasAnyRole('ROLE_SYSTEM_ADMINISTRATOR', 'ROLE_KEY_ACCOUNT_MANAGER', 'ROLE_A', 'ROLE_B')]
15:31:57,675 DEBUG [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] () Previously Authenticated: or
g.springframework.security.authentication.AnonymousAuthenticationToken#90579aae: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: tr
ue; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#2eb76: RemoteIpAddress: my machine ip address; SessionId: MdlIOjDwbSdN+e9r0-
6CEkxJ; Granted Authorities: ROLE_ANONYMOUS
15:31:57,690 DEBUG [org.springframework.security.access.vote.AffirmativeBased] () Voter: org.springframework.security.web.access
.expression.WebExpressionVoter#1d80d50, returned: -1
15:31:57,691 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] () Returning cached instance of single
ton bean 'org.springframework.context.annotation.internalScheduledAnnotationProcessor'
15:31:57,692 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] () Returning cached instance of single
ton bean 'org.springframework.scheduling.config.ContextLifecycleScheduledTaskRegistrar#0'
15:31:57,693 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] () Returning cached instance of single
ton bean 'sessionRegistry'
15:31:57,693 DEBUG [org.springframework.security.web.access.ExceptionTranslationFilter] () Access is denied (user is anonymous);
redirecting to authentication entry point: org.springframework.security.access.AccessDeniedException: Access is denied
at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:83) [spring-security-core-3.1.4.RELEASE.jar:3.1.4.RE
LEASE]
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:206) [spring-se
curity-core-3.1.4.RELEASE.jar:3.1.4.RELEASE]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115) [spring-security-web
-3.1.4.RELEASE.jar:3.1.4.RELEASE]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84) [spring-security-we
b-3.1.4.RELEASE.jar:3.1.4.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.1.4.RELEASE
.jar:3.1.4.RELEASE]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113) [spring-security-web-3.1.4
.RELEASE.jar:3.1.4.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.1.4.RELEASE
.jar:3.1.4.RELEASE]
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103) [spring-security-web-3.1.4.RELE
ASE.jar:3.1.4.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.1.4.RELEASE
.jar:3.1.4.RELEASE]
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113) [spring-secu
rity-web-3.1.4.RELEASE.jar:3.1.4.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.1.4.RELEASE
.jar:3.1.4.RELEASE]
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:5
4) [spring-security-web-3.1.4.RELEASE.jar:3.1.4.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.1.4.RELEASE
.jar:3.1.4.RELEASE]
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45) [spring-security-web-3.1.4.
RELEASE.jar:3.1.4.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.1.4.RELEASE
.jar:3.1.4.RELEASE]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java
:183) [spring-security-web-3.1.4.RELEASE.jar:3.1.4.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.1.4.RELEASE
.jar:3.1.4.RELEASE]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105) [spring-security-web-3.1.4.RELEASE.jar:
3.1.4.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.1.4.RELEASE
.jar:3.1.4.RELEASE]
at org.springframework.security.web.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:125) [spring-security-web-3.1.4.RELE
ASE.jar:3.1.4.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.1.4.RELEASE
.jar:3.1.4.RELEASE]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87) [spring-securi
ty-web-3.1.4.RELEASE.jar:3.1.4.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.1.4.RELEASE
.jar:3.1.4.RELEASE]
at org.springframework.security.web.access.channel.ChannelProcessingFilter.doFilter(ChannelProcessingFilter.java:144) [spring-security-web-3.1
.4.RELEASE.jar:3.1.4.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) [spring-security-web-3.1.4.RELEASE
.jar:3.1.4.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192) [spring-security-web-3.1.4.RELEASE.jar:3.1.4.
RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160) [spring-security-web-3.1.4.RELEASE.jar:3.1.4.RELEASE]
at org.springframework.security.config.debug.DebugFilter.invokeWithWrappedRequest(DebugFilter.java:69) [spring-security-config-3.1.4.RELEASE.j
ar:3.1.4.RELEASE]
at org.springframework.security.config.debug.DebugFilter.doFilter(DebugFilter.java:58) [spring-security-config-3.1.4.RELEASE.jar:3.1.4.RELEASE
]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) [spring-web-3.2.3.RELEASE.jar:3.2.3.REL
EASE]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259) [spring-web-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246) [jbossweb-7.2.0.Final-redhat-1.jar:7.2.0.
Final-redhat-1]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) [jbossweb-7.2.0.Final-redhat-1.jar:7.2.0.Final-re
dhat-1]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) [spring-web-3.2.3.RELEASE.jar:3.2.
3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-3.2.3.RELEASE.jar:3.2.3.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246) [jbossweb-7.2.0.Final-redhat-1.jar:7.2.0.
Final-redhat-1]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) [jbossweb-7.2.0.Final-redhat-1.jar:7.2.0.Final-re
dhat-1]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) [jbossweb-7.2.0.Final-redhat-1.jar:7.2.0.Final-redhat-1
]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:149) [jbossweb-7.2.0.Final-redhat-1.jar:7.2.0.Final-redhat-1
]
at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50) [jboss-as-jpa-7.2.0.Final-redhat-8.jar:7.2.0.Final
-redhat-8]
at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50) [jboss-as-jpa-7.2.0.Final-redhat-8.jar:7.2.0.Final
-redhat-8]
at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:169) [jboss-as-web-7.2.0.Final-redhat
-8.jar:7.2.0.Final-redhat-8]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:145) [jbossweb-7.2.0.Final-redhat-1.jar:7.2.0.Final-redhat-1]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:97) [jbossweb-7.2.0.Final-redhat-1.jar:7.2.0.Final-redhat-1]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:102) [jbossweb-7.2.0.Final-redhat-1.jar:7.2.0.Final-redhat-1]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:336) [jbossweb-7.2.0.Final-redhat-1.jar:7.2.0.Final-redhat-1]
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856) [jbossweb-7.2.0.Final-redhat-1.jar:7.2.0.Final-redhat-1]
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:653) [jbossweb-7.2.0.Final-redhat-1.jar:7.2.0.F
inal-redhat-1]
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:920) [jbossweb-7.2.0.Final-redhat-1.jar:7.2.0.Final-redhat-1]
at java.lang.Thread.run(Thread.java:619) [rt.jar:1.6.0_13]
We are using cookie header in response as httpOnly;Secure
I tried to add requires-channel="https" but it didn't worked either.
If you don't want this login-form to appear please remove the following maven-dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Hope this helps someone.
The problem is resolved : I was manually setting below header in my response to avoid security defects...due to this I was getting access denied exception.
I removed the below code and added at apache lavel and it worked fine.
String sessionid = request.getSession(true).getId();
resp.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid
+ "; Secure; HttpOnly");
resp.setHeader("Expires", "Tue, 14 May 1985 00:00:00 GMT");
resp.setHeader("Last-Modified", new Date().toString());
resp.setHeader(
"Cache-Control",
"no-store, no-cache, no-store, must-revalidate, max-age=0, post-check=0, pre-check=0");
resp.setHeader("Pragma", "no-cache");
resp.addHeader("X-FRAME-OPTIONS", "SAMEORIGIN");
resp.addHeader("strict-transport-security", "max-age=631138519");
resp.addHeader("x-xss-protection", "1; mode=block");
This error comes,if you have added (logback-classic/logback-classic) jar file in you lib.
Ex:
ch.qos.logback
logback-classic
${logback.version}
if you have mapped it or its dependacny jar then remove it to resolve "org.springframework.security.access.AccessDeniedException: Access is denied"

Spring security not intercepting request

I'm trying to do a basic spring security D/B authentication program.I tried this by two ways i.e.
Method 1 : Using custom tables for Spring Security authentication.
Method 2 : Using Spring security specific database tables for user authentication and authorization.
File Locations:
1. index.jsp -> webapp/index.jsp
2. welcome.jsp -> webapp/pages/welcome.jsp
3. login.jsp -> webapp/pages/login.jsp
For method 1,Spring security was not intercepting request and i didn't see errors in console.Instead of intercepting the request i was directly taken to welcome.jsp.
P.S - Since i was not trying authorization, i didn't use 'authorities-by-username-query' attribute below in security context xml. I'm not sure if its mandatory to create a table for authorization as well.
Below is my security-context.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:jee="http://www.springframework.org/schema/jee"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:tx="http://www.springframework.org/schema/tx"
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.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<security:http auto-config="true">
<security:intercept-url pattern="/welcome.html" />
<security:form-login login-page="/login.html"
default-target-url="/welcome.html" authentication-failure-url="/loginfailed.html" />
<security:logout logout-success-url="/logout.html" />
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:jdbc-user-service data-source-ref="dataSource"
users-by-username-query="select FIRST_NAME,LAST_NAME,PASSWORD from USER_AUTHENTICATION where FIRST_NAME=?" />
</security:authentication-provider>
</security:authentication-manager>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web- app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>SpringPOC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContextDirect.xml
/WEB-INF/applicationContext-security.xml
</param-value>
</context-param>
<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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
BaseController
//#RequestMapping(value="/login", method = RequestMethod.GET)
#RequestMapping("/login")
public ModelAndView login(Model model) {
//System.out.println("Inside /login...");
return new ModelAndView("login");
}
/*public String login(ModelMap model) {
System.out.println("Inside /login...");
return "login";
}*/
#RequestMapping(value="/loginfailed", method = RequestMethod.GET)
public String loginerror(ModelMap model) {
model.addAttribute("error", "true");
return "login";
}
#RequestMapping(value="/logout", method = RequestMethod.GET)
public String logout(ModelMap model) {
return "login";
}
login.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Login Page</title>
<style>
.errorblock {
color: #ff0000;
background-color: #ffEEEE;
border: 3px solid #ff0000;
padding: 8px;
margin: 16px;
}
</style>
</head>
<body onload='document.f.j_username.focus();'>
<h3>Login with Username and Password (Authentication with Database)</h3>
<c:if test="${not empty error}">
<div class="errorblock">
Your login attempt was not successful, try again.<br /> Caused :
${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
</div>
</c:if>
<form name='f' action="<c:url value='j_spring_security_check' />"
method='POST'>
<table>
<tr>
<td>User:</td>
<td><input type='text' name='j_username' value=''>
</td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='j_password' />
</td>
</tr>
<tr>
<td colspan='2'><input name="submit" type="submit"
value="submit" />
</td>
</tr>
<tr>
<td colspan='2'><input name="reset" type="reset" />
</td>
</tr>
</table>
</form>
index.jsp
<body>
<div id="content">
<h1>Home Page</h1>
<p>
Anyone can view this page.
</p>
<p>Login page</p>
</div>
</body>
For method 2, i created spring specific database tables in the name of “USERS” and “AUTHORITIES” after following the below link. Here SQL query is not used in xml as shown below.
http://www.raistudies.com/spring-security-tutorial/authentication-authorization-spring-security-mysql-database/
Every thing remains same except for security-context.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:jee="http://www.springframework.org/schema/jee"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:tx="http://www.springframework.org/schema/tx"
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.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<security:http realm="Project Realm" auto-config="true">
<security:intercept-url pattern="/welcome.html" access="ROLE_USER"/>
<security:form-login login-page="/login.html"
default-target-url="/welcome.html" authentication-failure-url="/loginfailed.html" />
<security:logout logout-success-url="/logout.html" />
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:password-encoder hash="md5"/>
<security:jdbc-user-service data-source-ref="dataSource"/>
</security:authentication-provider>
</security:authentication-manager>
</beans>
when i tried the above way, even though i enter correct user name & password, i was getting 'bad credentials' message [But yes, in this case spring security is intercepting the request]. I'm using Oracle database.
[Update]: I enabled spring debug logging to find the root cause of errors in both methods. I couldn't figure out or understand what exactly is wrong from logs, so i compared logs i got after trying both methods.As,for method 1 Spring security was not intercepting request and for method 2 i was able to login (Spring security was atleast intercepting request) but i was getting 'Bad credential' message even after entering correct username & password.
Below is the code snippet for method 2[ Here i get login page,but authentication is failing]
firing Filter: 'FilterSecurityInterceptor'
DEBUG: org.springframework.security.web.util.AntPathRequestMatcher - Checking match of request : '/welcome.html'; against
'/welcome.html'
DEBUG: org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Secure object: FilterInvocation: URL:
/welcome.html; Attributes: [ROLE_USER]
DEBUG: org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Previously Authenticated:
org.springframework.security.authentication.AnonymousAuthenticationToken#9055c2bc: Principal: anonymousUser; Credentials:
[PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#b364:
RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
DEBUG: org.springframework.security.access.vote.AffirmativeBased - Voter:
org.springframework.security.access.vote.RoleVoter#19432e0, returned: -1
DEBUG: org.springframework.security.access.vote.AffirmativeBased - Voter:
org.springframework.security.access.vote.AuthenticatedVoter#9830bc, returned: 0
DEBUG: org.springframework.security.web.access.ExceptionTranslationFilter - Access is denied (user is anonymous);
redirecting to authentication entry point
org.springframework.security.access.AccessDeniedException: Access is denied
at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:83)
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation
(AbstractSecurityInterceptor.java:206)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke
(FilterSecurityInterceptor.java:115)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter
(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter
(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter
(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter
(BasicAuthenticationFilter.java:150)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter
(AbstractAuthenticationProcessingFilter.java:183)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter
(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)
DEBUG: org.springframework.security.web.savedrequest.HttpSessionRequestCache - DefaultSavedRequest added to Session:
DefaultSavedRequest[http://localhost:8080/itrade-web/welcome.html]
DEBUG: org.springframework.security.web.access.ExceptionTranslationFilter - Calling Authentication entry point.
DEBUG: org.springframework.security.web.DefaultRedirectStrategy - Redirecting to 'http://localhost:8080/itrade-
web/login.html;jsessionid=3FD72892F4F4EF2E65B0C90ABE115354'
DEBUG: org.springframework.security.web.context.HttpSessionSecurityContextRepository - SecurityContext is empty or contents
are anonymous - context will not be stored in HttpSession.
DEBUG: org.springframework.security.web.context.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as
request processing completed
DEBUG: org.springframework.security.web.FilterChainProxy - /login.html at position 1 of 10 in additional filter chain;
firing Filter: 'SecurityContextPersistenceFilter'
DEBUG: org.springframework.security.web.context.HttpSessionSecurityContextRepository - HttpSession returned null object for SPRING_SECURITY_CONTEXT
firing Filter: 'UsernamePasswordAuthenticationFilter'
...
DEBUG: org.springframework.security.web.FilterChainProxy - /login.html at position 7 of 10 in additional filter chain;
firing Filter: 'AnonymousAuthenticationFilter'
DEBUG: org.springframework.security.web.authentication.AnonymousAuthenticationFilter - Populated SecurityContextHolder with
anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken#6fa8940c: Principal:
anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details:
org.springframework.security.web.authentication.WebAuthenticationDetails#fffde5d4: RemoteIpAddress: 0:0:0:0:0:0:0:1;
SessionId: 3FD72892F4F4EF2E65B0C90ABE115354; Granted Authorities: ROLE_ANONYMOUS'
...
DEBUG: org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - Request is to process
authentication
DEBUG: org.springframework.security.authentication.ProviderManager - Authentication attempt using
org.springframework.security.authentication.dao.DaoAuthenticationProvider
DEBUG: org.springframework.security.provisioning.JdbcUserDetailsManager - Query returned no results for user 'admin'
DEBUG: org.springframework.security.authentication.dao.DaoAuthenticationProvider - User 'admin' not found
DEBUG: org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - Authentication request
failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials
DEBUG: org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - Updated SecurityContextHolder
to contain null Authentication
DEBUG: org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - Delegating to authentication
failure handler org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler#1882c1a
DEBUG: org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler - Redirecting to
/loginfailed.html
DEBUG: org.springframework.security.web.DefaultRedirectStrategy - Redirecting to '/itrade-web/loginfailed.html'
DEBUG: org.springframework.security.web.context.HttpSessionSecurityContextRepository - SecurityContext is empty or contents
are anonymous - context will not be stored in HttpSession.
DEBUG: org.springframework.security.web.context.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as
request processing completed
[Update] For method 1 ,i added 'authorities-by-username-query' tag after creating a custom table for 'authorization'. Now i'm getting login screen, so i got to know inorder for spring security to intercept i need to have 'authorities-by-username-query' tag .But after entering user name and password i get following error mesage :
Caused : PreparedStatementCallback; uncategorized SQLException for SQL [select FIRST_NAME,LAST_NAME,PASSWORD from USER_AUTHENTICATION where FIRST_NAME=?]; SQL state [null]; error code [17059]; Fail to convert to internal representation; nested exception is java.sql.SQLException: Fail to convert to internal representation
i see following lines in debug mode :
DEBUG: org.springframework.security.authentication.ProviderManager - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [org/springframework/jdbc/support/sql-error-codes.xml]
DEBUG: org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - Authentication request failed: org.springframework.security.authentication.AuthenticationServiceException: PreparedStatementCallback; uncategorized SQLException for SQL [select FIRST_NAME,LAST_NAME,PASSWORD from USER_AUTHENTICATION where FIRST_NAME=?]; SQL state [null]; error code [17059]; Fail to convert to internal representation; nested exception is java.sql.SQLException: Fail to convert to internal representation
DEBUG: org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - Updated SecurityContextHolder to contain null Authentication
DEBUG: org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - Delegating to authentication failure handler org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler#e7736c
DEBUG: org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler - Redirecting to /loginfailed.html
DEBUG: org.springframework.security.web.DefaultRedirectStrategy - Redirecting to '/itrade-web/loginfailed.html'
[Update]: Now for both methods i'm getting same error though i enter correct user name & password.Also,since i could fetch data from D/B i'm sure that I'm not going wrong because of data not present in D/B.
DEBUG: org.springframework.security.provisioning.JdbcUserDetailsManager - Query returned no results for user 'user'
I feel there should be any other reason behind this error.
[Edit] Now I've following 'users_detail' table in D/B :
USER_ID INTEGER
USERNAME VARCHAR2 (50 Byte)
PASSWORD VARCHAR2 (50 Byte)
ENABLED INTEGER
Data in the 'users_detail' table :
USER_ID USERNAME PASSWORD ENABLED
100 user 123456 1
My query is in security-context.xml :
"select username,password, enabled from users_detail where username=?"
when i execute the query manually i.e. select username,password,enabled from users_detail where username='user'. i get the resultsets.
Where am i going wrong ? Why is it that JdbcUserDetailsManager class always return 'Query returned no results for user 'user' ' even though there is an entry for the same in D/B.
Debug mode doesn't show which method of JdbcUserDetailsManager class is being executed when i get the above error. How can i know that? Also, does spring internally do any encryption/decryption technique while saving password field?
The log message "User 'admin' not found" seems pretty clear as a reason for authentication failure, when using the default schema. Why not just execute the command manually and see if it returns the user data?
Also, whether the login screen is shown doesn't depend on whether you set "'authorities-by-username-query" or not. It only depends on whether what intercept-url values apply for the URL you request. The only exception would be if you have customized the access-denied behaviour (for an authenticated user with insufficient rights) to show the login page (not the case here).
Your SQL exception is probably due to your custom table having the wrong column types. You need to end up with something compatible with the result set obtained from the standard schema. Better to stick with the default unless you have a good reason not to.
Better still, forget about Oracle completely until you can get the basics working with a simple test database like HSQLDB.

Spring Security remember-me re login fails

I'm trying to create remember-me based on persistent token approach feature. as my dataSource I have mongoDB. In order to store tokens in as collection I override PersistentTokenRepository class and it seems to be ok, but I can't login when I reopen my browser. I'm using mongoDB to store tokens, but it shouldn't be a problem all db layer functions work as expected.
My spring security configuration looks like this:
<security:global-method-security secured-annotations="enabled" />
<security:http pattern="/login.html" security="none"/>
<security:http pattern="/signup.html" security="none"/>
<security:http auto-config="true" access-denied-page="/accessDenied.jsp">
<security:form-login login-page="/login.html" login-processing-url="/login" authentication-failure-url="/login.html?login_error=1" default-target-url="/"/>
<security:http-basic/>
<security:intercept-url pattern='/**' access='ROLE_USER' />
<security:logout logout-url="/logout" logout-success-url="/"/>
<security:remember-me services-ref="rememberMeServices"/>
</security:http>
<bean id="userPassAuthFilterBeanPostProcessor"
class="com.mytwitter.web.security.UserPassAuthFilterBeanPostProcessor">
<property name="usernameParameter" value="username" />
<property name="passwordParameter" value="password" />
</bean>
<bean id="LoginUrlAuthenticationEntryPoint"
class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<property name="loginFormUrl" value="/login" />
</bean>
<bean id="daoAuthenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userDetailsService"/>
</bean>
<bean id="authenticationManager"
class="org.springframework.security.authentication.ProviderManager">
<property name="providers">
<list>
<ref local="daoAuthenticationProvider" />
</list>
</property>
</bean>
<security:authentication-manager alias="authManager">
<security:authentication-provider user-service-ref="userDetailsService">
<security:password-encoder hash="md5"/>
</security:authentication-provider>
</security:authentication-manager>
<bean id="rememberMeServices" class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices">
<property name="tokenRepository" ref="myTokenRepository" />
<property name="userDetailsService" ref="userDetailsService" />
<property name="key" value="myRememberMeKey" />
<property name="alwaysRemember" value="true" />
</bean>
<bean id="myTokenRepository" class="com.mytwitter.web.security.MyTokenRepository">
</bean>
When I login correctly my token inserted into Database. I can see it clearly.
After I close the browser and trying re-login authentication fails.
There is no problem with mongoDB all queries executed successfully.
When I turn on debuging I see the following behavior:
2012-02-05 00:33:54,374 DEBUG [http-bio-8080-exec-7] org.springframework.security.web.FilterChainProxy - /index.jsp at position 7 of 11 in additional filter chain; firing Filter: 'RememberMeAuthenticationFilter' - 287265
2012-02-05 00:33:59,801 DEBUG [http-bio-8080-exec-7] org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices - Remember-me cookie detected - 292692
getting Token
2012-02-05 00:34:04,829 DEBUG [http-bio-8080-exec-7] org.springframework.data.mongodb.core.MongoTemplate - findOne using query: { "series" : "qhvYe8ZsDX+72ZbeNxSGzQ=="} in db.collection: xxx.rememberMeTokens - 297720
2012-02-05 00:34:21,471 DEBUG [http-bio-8080-exec-7] org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices - Refreshing persistent login token for user 'aaaa', series 'qhvYe8ZsDX+72ZbeNxSGzQ==' - 314362
Updating Token
2012-02-05 00:34:23,043 DEBUG [http-bio-8080-exec-7] org.springframework.data.mongodb.core.MongoTemplate - calling update using query: { "series" : "qhvYe8ZsDX+72ZbeNxSGzQ=="} and update: { "$set" : { "token" : "LVBRYo/vjEARdm262UA07g==" , "last_used" : { "$date" : "2012-02-04T22:34:22.333Z"}}} in collection: persistentRememberMeToken - 315934
2012-02-05 00:34:26,427 DEBUG [http-bio-8080-exec-7] org.springframework.data.mongodb.core.MongoTemplate - findOne using query: { "nickname" : "aaaa"} in db.collection: xxxx.users - 319318
2012-02-05 00:34:45,623 DEBUG [http-bio-8080-exec-7] org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices - Remember-me cookie accepted - 338514
2012-02-05 00:36:24,438 DEBUG [http-bio-8080-exec-7] org.springframework.security.authentication.ProviderManager - Authentication attempt using org.springframework.security.authentication.RememberMeAuthenticationProvider - 437329
2012-02-05 00:36:45,543 DEBUG [http-bio-8080-exec-7] org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter - SecurityContextHolder not populated with remember-me token, as AuthenticationManager rejected Authentication returned by RememberMeServices: 'org.springframework.security.authentication.RememberMeAuthenticationToken#7609e07a: Principal: com.mytwitter.web.security.AuthUser#3214512e; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_USER'; invalidating remember-me token - 458434
org.springframework.security.authentication.BadCredentialsException: The presented RememberMeAuthenticationToken does not contain the expected key
at org.springframework.security.authentication.RememberMeAuthenticationProvider.authenticate(RememberMeAuthenticationProvider.java:64)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:102)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:182)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:173)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:964)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:679)
What am I missing?
Today after I reboot my laptop and started tomcat + eclipse it works ok and no error occurs. I'm quite confused with this behavior, but god gave me courage to accept things that I can't understand,but I believe that it has something to do with the old cookies for this site. Now when all of them expired it works fine.

Resources