LazyInitializationException despite of OpenSessionInViewFilter - spring

I develop webapp using Spring 4, Hibernate 4 and JSF 2.2. I'm trying to use OpenSessionInViewFilter to avoid LazyInitializationException but I fail. I have class Consultant with such field:
#OneToMany(fetch = FetchType.LAZY, mappedBy = "consultant")
private List<Product> products;
Now in other class where I have my Consultant object and I'm trying to get products using above field:
List<Product> products = consultant.getProducts();
Then LazyInitializationException is thrown. It's my log (I can't see any suspect things there):
Using SessionFactory 'sessionFactory' for OpenSessionInViewFilter
Returning cached instance of singleton bean 'sessionFactory'
Opening Hibernate Session in OpenSessionInViewFilter
/consultant/products.xhtml at position 1 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'org.springframework.security.core.context.SecurityContextImpl#f8b7e57f: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#f8b7e57f: Principal: User{userId=1, username=doradca#doradca.pl, password=$2a$10$ALqnZKxx9anO/4XnBjtt1Ocm4GC1KDfrAlIz/iV66RWANklk31WqW, authorities=[Authority{role=CONSULTANT}], accountNonExpired=true, accountNonLocked=true, credentialsNonExpired=true, enabled=true}; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#2cd90: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 9ED9D61F10507CAF3B77109D465B9AD6; Granted Authorities: Authority{role=CONSULTANT}'
/consultant/products.xhtml at position 2 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
/consultant/products.xhtml at position 3 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
/consultant/products.xhtml at position 4 of 11 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
/consultant/products.xhtml at position 5 of 11 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
/consultant/products.xhtml at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
pathInfo: both null (property equals)
queryString: both null (property equals)
requestURI: arg1=/EuroBroker/consultant/products.xhtml; arg2=/EuroBroker/consultant/products.xhtml (property equals)
serverPort: arg1=8080; arg2=8080 (property equals)
requestURL: arg1=http://localhost:8080/EuroBroker/consultant/products.xhtml; arg2=http://localhost:8080/EuroBroker/consultant/products.xhtml (property equals)
scheme: arg1=http; arg2=http (property equals)
serverName: arg1=localhost; arg2=localhost (property equals)
contextPath: arg1=/EuroBroker; arg2=/EuroBroker (property equals)
servletPath: arg1=/consultant/products.xhtml; arg2=/consultant/products.xhtml (property equals)
Removing DefaultSavedRequest from session if present
/consultant/products.xhtml at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
/consultant/products.xhtml at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken#f8b7e57f: Principal: User{userId=1, username=doradca#doradca.pl, password=$2a$10$ALqnZKxx9anO/4XnBjtt1Ocm4GC1KDfrAlIz/iV66RWANklk31WqW, authorities=[Authority{role=CONSULTANT}], accountNonExpired=true, accountNonLocked=true, credentialsNonExpired=true, enabled=true}; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#2cd90: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 9ED9D61F10507CAF3B77109D465B9AD6; Granted Authorities: Authority{role=CONSULTANT}'
/consultant/products.xhtml at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
/consultant/products.xhtml at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
/consultant/products.xhtml at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
Checking match of request : '/consultant/products.xhtml'; against '/consultant/**'
Secure object: FilterInvocation: URL: /consultant/products.xhtml; Attributes: [hasRole('CONSULTANT')]
Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#f8b7e57f: Principal: User{userId=1, username=doradca#doradca.pl, password=$2a$10$ALqnZKxx9anO/4XnBjtt1Ocm4GC1KDfrAlIz/iV66RWANklk31WqW, authorities=[Authority{role=CONSULTANT}], accountNonExpired=true, accountNonLocked=true, credentialsNonExpired=true, enabled=true}; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#2cd90: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 9ED9D61F10507CAF3B77109D465B9AD6; Granted Authorities: Authority{role=CONSULTANT}
Voter: org.springframework.security.web.access.expression.WebExpressionVoter#16ed6204, returned: 1
Authorization successful
RunAsManager did not change Authentication object
/consultant/products.xhtml reached end of additional filter chain; proceeding with original chain
Entering JSF Phase: RESTORE_VIEW 1
Entering JSF Phase: RENDER_RESPONSE 6
Returning cached instance of singleton bean 'org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler#0'
Returning cached instance of singleton bean 'org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler#0'
Returning cached instance of singleton bean 'org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler#0'
Returning cached instance of singleton bean 'accountManager'
Returning cached instance of singleton bean 'insuranceService'
Returning cached instance of singleton bean 'insuranceService'
Chain processed normally
SecurityContextHolder now cleared, as request processing completed
Closing Hibernate Session in OpenSessionInViewFilter
com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector#373d727a -- Running DeadlockDetector[Exiting. No pending tasks.]
Returning cached instance of singleton bean 'transactionManager'
Creating new transaction with name [com.efsf.eurobroker.user.logic.TokenCleanerCron.deleteOldTokens]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
Opened new Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[] unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])] for Hibernate transaction
Preparing JDBC Connection of Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[] unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])]
trace com.mchange.v2.resourcepool.BasicResourcePool#6383a319 [managed: 5, unused: 4, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection#4c7576d0)
Exposing Hibernate transaction as JDBC transaction [com.mchange.v2.c3p0.impl.NewProxyConnection#330b16dd]
Returning cached instance of singleton bean 'transactionManager'
Found thread-bound Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[] unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])] for Hibernate transaction
Participating in existing transaction
com.mchange.v2.c3p0.stmt.GlobalMaxOnlyStatementCache ----> CACHE HIT
checkoutStatement: com.mchange.v2.c3p0.stmt.GlobalMaxOnlyStatementCache stats -- total size: 4; checked out: 1; num connections: 1; num keys: 4
checkinStatement(): com.mchange.v2.c3p0.stmt.GlobalMaxOnlyStatementCache stats -- total size: 4; checked out: 0; num connections: 1; num keys: 4
Initiating transaction commit
Committing Hibernate transaction on Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[] unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])]
Closing Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[] unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])] after transaction
checkinAll(): com.mchange.v2.c3p0.stmt.GlobalMaxOnlyStatementCache stats -- total size: 4; checked out: 0; num connections: 1; num keys: 4
com.mchange.v2.async.ThreadPoolAsynchronousRunner#7f0b008a: Adding task to queue -- com.mchange.v2.resourcepool.BasicResourcePool$1RefurbishCheckinResourceTask#5149a61d
trace com.mchange.v2.resourcepool.BasicResourcePool#6383a319 [managed: 5, unused: 4, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection#4c7576d0)
checkinAll(): com.mchange.v2.c3p0.stmt.GlobalMaxOnlyStatementCache stats -- total size: 4; checked out: 0; num connections: 1; num keys: 4
com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector#373d727a -- Running DeadlockDetector[Exiting. No pending tasks.]
com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector#373d727a -- Running DeadlockDetector[Exiting. No pending tasks.]
In web.xml I addded (before any other filters):
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
How do I get exception and how to avoid this one? I tried also OpenSessionInViewInterceptor but didn't work or I was doing something wrong.
I spent many many hours trying to solve this problem, reading many topics and tutorials but nothing helped me.
Thank you in advance for any help.

Related

Actuator and OAuth2 in ResourceServer

I have a ResourceServer defined which is currently validating an AccessToken using a public key. This is working as expected.
I would like to retain the sensitivity behavior of the Actuator endpoints and use OAuth for the Sensitive endpoints.
The default behavior in Spring boot is using some form of Basic Auth to secure the Actuator endpoints. How can I switch to OAuth for the Sensitive Endpoints?
Things I have tried:
management.security.enabled=false (disables all form of security to all the Actuator endpoints)
security.basic.enabled=false (doesn't seem to do anything at all afaik)
How do I go about achieving the desired behavior?
Edit-1: Adding the configuration of the ResourceServer
#Configuration
#EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
}
# OAuth2 Resource Configuration
security.oauth2.resource.filter-order=3
security.oauth2.resource.jwt.key-value=-----BEGIN PUBLIC KEY----- \
ABCD|\
-----END PUBLIC KEY-----
Edit-2: Logs with management.security.enabled=false
2018-04-04 09:38:52,428 [restartedMain ] INFO o.s.s.w.DefaultSecurityFilterChain.<init>(ln:43) - Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/css/**'], Ant [pattern='/js/**'], Ant [pattern='/images/**'], Ant [pattern='/webjars/**'], Ant [pattern='/**/favicon.ico'], Ant [pattern='/error']]], []
2018-04-04 09:38:52,428 [restartedMain ] INFO o.s.s.w.DefaultSecurityFilterChain.<init>(ln:43) - Creating filter chain: org.springframework.boot.actuate.autoconfigure.ManagementWebSecurityAutoConfiguration$LazyEndpointPathRequestMatcher#cba0b40, []
2018-04-04 09:38:52,517 [restartedMain ] DEBUG o.s.s.w.a.e.ExpressionBasedFilterInvocationSecurityMetadataSource.processMap(ln:74) - Adding web access control expression 'hasAnyRole('ROLE_USER','ROLE_ACTUATOR')', for org.springframework.security.web.util.matcher.AnyRequestMatcher#1
2018-04-04 09:38:52,527 [restartedMain ] DEBUG o.s.s.a.i.AbstractSecurityInterceptor.afterPropertiesSet(ln:180) - Validated configuration attributes
2018-04-04 09:38:52,528 [restartedMain ] DEBUG o.s.s.a.i.AbstractSecurityInterceptor.afterPropertiesSet(ln:180) - Validated configuration attributes
2018-04-04 09:38:52,537 [restartedMain ] INFO o.s.s.w.DefaultSecurityFilterChain.<init>(ln:43) - Creating filter chain: Ant [pattern='/h2-console/**'], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#2f0907e7, org.springframework.security.web.context.SecurityContextPersistenceFilter#7d0c8fcd, org.springframework.security.web.header.HeaderWriterFilter#1deb6ece, org.springframework.security.web.authentication.logout.LogoutFilter#54ae565a, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#101e66ff, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#48870c1e, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#2c3aa8cc, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#43db62cc, org.springframework.security.web.session.SessionManagementFilter#1c417a06, org.springframework.security.web.access.ExceptionTranslationFilter#6af61e6, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#e2595cc]
2018-04-04 09:38:52,559 [restartedMain ] DEBUG o.s.s.w.a.e.ExpressionBasedFilterInvocationSecurityMetadataSource.processMap(ln:74) - Adding web access control expression 'authenticated', for org.springframework.security.web.util.matcher.AnyRequestMatcher#1
2018-04-04 09:38:52,560 [restartedMain ] DEBUG o.s.s.a.i.AbstractSecurityInterceptor.afterPropertiesSet(ln:180) - Validated configuration attributes
2018-04-04 09:38:52,560 [restartedMain ] DEBUG o.s.s.a.i.AbstractSecurityInterceptor.afterPropertiesSet(ln:180) - Validated configuration attributes
2018-04-04 09:38:52,561 [restartedMain ] INFO o.s.s.w.DefaultSecurityFilterChain.<init>(ln:43) - Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher#1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#71c85f60, org.springframework.security.web.context.SecurityContextPersistenceFilter#3867025d, org.springframework.security.web.header.HeaderWriterFilter#1fe578f, org.springframework.security.web.authentication.logout.LogoutFilter#6bcc7bbf, org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter#52f4e578, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#2a57cae0, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#5966b20a, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#10e17172, org.springframework.security.web.session.SessionManagementFilter#440ed2d3, org.springframework.security.web.access.ExceptionTranslationFilter#76cc8ddc, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#72a6a42e]
2018-04-04 09:38:52,565 [restartedMain ] DEBUG o.s.s.w.a.e.ExpressionBasedFilterInvocationSecurityMetadataSource.processMap(ln:74) - Adding web access control expression 'hasAnyRole('ROLE_USER','ROLE_ACTUATOR')', for org.springframework.security.web.util.matcher.AnyRequestMatcher#1
2018-04-04 09:38:52,566 [restartedMain ] DEBUG o.s.s.a.i.AbstractSecurityInterceptor.afterPropertiesSet(ln:180) - Validated configuration attributes
2018-04-04 09:38:52,566 [restartedMain ] DEBUG o.s.s.a.i.AbstractSecurityInterceptor.afterPropertiesSet(ln:180) - Validated configuration attributes
2018-04-04 09:38:52,567 [restartedMain ] INFO o.s.s.w.DefaultSecurityFilterChain.<init>(ln:43) - Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/**']]], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#3b9584b5, org.springframework.security.web.context.SecurityContextPersistenceFilter#2181d916, org.springframework.security.web.header.HeaderWriterFilter#5ed5886a, org.springframework.security.web.authentication.logout.LogoutFilter#74909e09, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#5b76b0e4, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#7c129fed, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#ef6dedd, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#6c8179fb, org.springframework.security.web.session.SessionManagementFilter#4d36e557, org.springframework.security.web.access.ExceptionTranslationFilter#1868a4d7, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#15c448ac]
2018-04-04 09:39:53,545 [nio-8080-exec-1] DEBUG o.s.s.w.u.m.OrRequestMatcher.matches(ln:65) - Trying to match using Ant [pattern='/metrics']
2018-04-04 09:39:53,545 [nio-8080-exec-1] DEBUG o.s.s.w.u.m.AntPathRequestMatcher.matches(ln:157) - Checking match of request : '/metrics'; against '/metrics'
2018-04-04 09:39:53,545 [nio-8080-exec-1] DEBUG o.s.s.w.u.m.OrRequestMatcher.matches(ln:68) - matched
2018-04-04 09:39:53,545 [nio-8080-exec-1] DEBUG o.s.s.w.FilterChainProxy.doFilterInternal(ln:201) - /metrics has an empty filter list
2018-04-04 09:41:57,195 [nio-8080-exec-5] DEBUG o.s.s.w.FilterChainProxy$VirtualFilterChain.doFilter(ln:325) - /customers at position 5 of 11 in additional filter chain; firing Filter: 'OAuth2AuthenticationProcessingFilter'
2018-04-04 09:41:57,196 [nio-8080-exec-5] DEBUG o.s.s.o.p.a.BearerTokenExtractor.extractToken(ln:54) - Token not found in headers. Trying request parameters.
2018-04-04 09:41:57,196 [nio-8080-exec-5] DEBUG o.s.s.o.p.a.BearerTokenExtractor.extractToken(ln:57) - Token not found in request parameters. Not an OAuth2 request.
2018-04-04 09:41:57,196 [nio-8080-exec-5] DEBUG o.s.s.o.p.a.OAuth2AuthenticationProcessingFilter.doFilter(ln:141) - No token in request, will continue chain.
2018-04-04 09:41:57,196 [nio-8080-exec-5] DEBUG o.s.s.w.FilterChainProxy$VirtualFilterChain.doFilter(ln:325) - /customers at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2018-04-04 09:41:57,196 [nio-8080-exec-5] DEBUG o.s.s.w.FilterChainProxy$VirtualFilterChain.doFilter(ln:325) - /customers at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2018-04-04 09:41:57,198 [nio-8080-exec-5] DEBUG o.s.s.w.FilterChainProxy$VirtualFilterChain.doFilter(ln:325) - /customers at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2018-04-04 09:41:57,198 [nio-8080-exec-5] DEBUG o.s.s.w.a.AnonymousAuthenticationFilter.doFilter(ln:100) - Populated SecurityContextHolder with anonymous token: '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'
2018-04-04 09:41:57,199 [nio-8080-exec-5] DEBUG o.s.s.w.FilterChainProxy$VirtualFilterChain.doFilter(ln:325) - /customers at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
2018-04-04 09:41:57,199 [nio-8080-exec-5] DEBUG o.s.s.w.s.SessionManagementFilter.doFilter(ln:124) - Requested session ID A2BB697A35FC287599CE86AA715115CA is invalid.
2018-04-04 09:41:57,199 [nio-8080-exec-5] DEBUG o.s.s.w.FilterChainProxy$VirtualFilterChain.doFilter(ln:325) - /customers at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2018-04-04 09:41:57,199 [nio-8080-exec-5] DEBUG o.s.s.w.FilterChainProxy$VirtualFilterChain.doFilter(ln:325) - /customers at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2018-04-04 09:41:57,200 [nio-8080-exec-5] DEBUG o.s.s.a.i.AbstractSecurityInterceptor.beforeInvocation(ln:219) - Secure object: FilterInvocation: URL: /customers; Attributes: [#oauth2.throwOnError(authenticated)]
2018-04-04 09:41:57,200 [nio-8080-exec-5] DEBUG o.s.s.a.i.AbstractSecurityInterceptor.authenticateIfRequired(ln:348) - 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
2018-04-04 09:41:57,205 [nio-8080-exec-5] DEBUG o.s.s.a.v.AffirmativeBased.decide(ln:66) - Voter: org.springframework.security.web.access.expression.WebExpressionVoter#794e8437, returned: -1
2018-04-04 09:41:57,207 [nio-8080-exec-5] DEBUG o.s.s.w.a.ExceptionTranslationFilter.handleSpringSecurityException(ln:173) - Access is denied (user is anonymous); redirecting to authentication entry point
org.springframework.security.access.AccessDeniedException: Access is denied
The brute force way is to just explicitly secure your actuator endpoints in your WebSecurityConfigurerAdapter. Something like this should do it:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.and()
.httpBasic().disable()
.anonymous().disable()
.authorizeRequests().anyRequest().authenticated();
}
Have a look at this tutorial. Following on from that, you should be able to secure any endpoint with an appropriate matcher in the configuration.

Why is formlogin with second precedence not working when configured with httpbasic with first precedence in spring boot? [duplicate]

This question already has answers here:
Spring Security : Multiple HTTP Config not working
(2 answers)
Closed 6 years ago.
I have an application that exposes "api" services and "web" pages. So, I've configured httpbasic and formlogin as per Spring's documentation (and from various other SO posts)
http://docs.spring.io/spring-security/site/docs/3.2.x/reference/htmlsingle/#multiple-httpsecurity
Spring Security HTTP Basic for RESTFul and FormLogin (Cookies) for web - Annotations
Below is my custom web security configurer code
#EnableWebSecurity
public class MySecurityConfiguration extends WebSecurityConfigurerAdapter {
private final Logger log = LoggerFactory.getLogger(this.getClass());
#Autowired
private MyAuthenticationProvider myAuthenticationProvider;
#Autowired
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(myAuthenticationProvider);
}
#Configuration
#Order(1)
public static class BasicAuthentication extends WebSecurityConfigurerAdapter{
private final Logger log = LoggerFactory.getLogger(this.getClass());
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/myapp/api/**").authenticated()
.and() // Permit access for all to login REST service
.httpBasic()
.authenticationEntryPoint(new MyAuthenticationFailurePoint());
}
}
#Configuration
#Order(2)
public static class FormAuthentication extends WebSecurityConfigurerAdapter{
private final Logger log = LoggerFactory.getLogger(this.getClass());
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/myapp/web/**").authenticated()
.and()
.formLogin()
.loginPage("/myapp/web/login")
.permitAll()
.and()
.logout()
.logoutUrl("/myapp/web/logout")
.permitAll();
}
}
}
With this code, when I consume (GET) "http:/ /localhost:8083/myapp/api/getIds", the logic works as expected and my custom authentication provider gets called. Please find below the
logs for your reference
[DEBUG] 2016-12-21 04:36:08.878 org.springframework.security.web.FilterChainProxy - /myapp/api/getIds at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
[DEBUG] 2016-12-21 04:36:08.904 org.springframework.security.web.FilterChainProxy - /myapp/api/getIds at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
[DEBUG] 2016-12-21 04:36:08.928 org.springframework.security.web.context.HttpSessionSecurityContextRepository - No HttpSession currently exists
[DEBUG] 2016-12-21 04:36:08.928 org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: null. A new one will be created.
[DEBUG] 2016-12-21 04:36:09.029 org.springframework.security.web.FilterChainProxy - /myapp/api/getIds at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
[DEBUG] 2016-12-21 04:36:09.030 org.springframework.security.web.header.writers.HstsHeaderWriter - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#3b41e91a
[DEBUG] 2016-12-21 04:36:09.030 org.springframework.security.web.FilterChainProxy - /myapp/api/getIds at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
[DEBUG] 2016-12-21 04:36:09.030 org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/myapp/api/getids'; against '/logout'
[DEBUG] 2016-12-21 04:36:09.030 org.springframework.security.web.FilterChainProxy - /myapp/api/getIds at position 5 of 11 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
[DEBUG] 2016-12-21 04:36:09.089 org.springframework.security.web.authentication.www.BasicAuthenticationFilter - Basic Authentication Authorization header found for user 'testuser'
[DEBUG] 2016-12-21 04:36:09.166 org.springframework.security.authentication.ProviderManager - Authentication attempt using com.myapp.inf.authenticator.MyAuthenticationProvider
[TRACE] 2016-12-21 04:36:33.498 org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext - Publishing event in org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#13330ac6: org.springframework.security.authentication.event.AuthenticationSuccessEvent[source=org.springframework.security.authentication.UsernamePasswordAuthenticationToken#fa787cf9: Principal: testuser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Not granted any authorities]
[DEBUG] 2016-12-21 04:36:33.498 org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'delegatingApplicationListener'
[DEBUG] 2016-12-21 04:36:33.499 org.springframework.security.web.authentication.www.BasicAuthenticationFilter - Authentication success: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#fa787cf9: Principal: testuser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Not granted any authorities
[DEBUG] 2016-12-21 04:36:33.499 org.springframework.security.web.FilterChainProxy - /myapp/api/getIds at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
[DEBUG] 2016-12-21 04:36:33.499 org.springframework.security.web.FilterChainProxy - /myapp/api/getIds at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
[DEBUG] 2016-12-21 04:36:33.551 org.springframework.security.web.FilterChainProxy - /myapp/api/getIds at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
[DEBUG] 2016-12-21 04:36:33.551 org.springframework.security.web.authentication.AnonymousAuthenticationFilter - SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken#fa787cf9: Principal: testuser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Not granted any authorities'
[DEBUG] 2016-12-21 04:36:33.551 org.springframework.security.web.FilterChainProxy - /myapp/api/getIds at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
[DEBUG] 2016-12-21 04:36:33.551 org.springframework.security.web.authentication.session.CompositeSessionAuthenticationStrategy - Delegating to org.springframework.security.web.authentication.session.ChangeSessionIdAuthenticationStrategy#46bf4560
[DEBUG] 2016-12-21 04:36:33.583 org.springframework.security.web.context.HttpSessionSecurityContextRepository - HttpSession being created as SecurityContext is non-default
[DEBUG] 2016-12-21 04:36:33.835 org.springframework.security.web.context.HttpSessionSecurityContextRepository - SecurityContext 'org.springframework.security.core.context.SecurityContextImpl#fa787cf9: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#fa787cf9: Principal: testuser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Not granted any authorities' stored to HttpSession: 'org.apache.catalina.session.StandardSessionFacade#2c175127
[DEBUG] 2016-12-21 04:36:33.835 org.springframework.security.web.FilterChainProxy - /myapp/api/getIds at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
[DEBUG] 2016-12-21 04:36:33.835 org.springframework.security.web.FilterChainProxy - /myapp/api/getIds at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
[DEBUG] 2016-12-21 04:36:33.860 org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/myapp/api/getids'; against '/myapp/api/**'
[DEBUG] 2016-12-21 04:36:33.860 org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Secure object: FilterInvocation: URL: /myapp/api/getIds; Attributes: [authenticated]
[DEBUG] 2016-12-21 04:36:33.860 org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#fa787cf9: Principal: testuser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Not granted any authorities
[DEBUG] 2016-12-21 04:36:34.082 org.springframework.security.access.vote.AffirmativeBased - Voter: org.springframework.security.web.access.expression.WebExpressionVoter#5169d120, returned: 1
[DEBUG] 2016-12-21 04:36:34.082 org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Authorization successful
[DEBUG] 2016-12-21 04:36:34.082 org.springframework.security.web.access.intercept.FilterSecurityInterceptor - RunAsManager did not change Authentication object
[DEBUG] 2016-12-21 04:36:34.083 org.springframework.security.web.FilterChainProxy - /myapp/api/getIds reached end of additional filter chain; proceeding with original chain
Now, when I hit (from browser) "http:/ /localhost:8083/myapp/web/MainConsole", I'm not being prompted for a login page. Please find below the logs for this hit. They indicate that spring boot
is using "httpbasic" config for this hit
[DEBUG] 2016-12-21 04:41:30.179 [http-nio-8083-exec-3] org.springframework.boot.context.web.OrderedRequestContextFilter - Bound request context to thread: org.apache.catalina.connector.RequestFacade#26ff703a
[DEBUG] 2016-12-21 04:41:30.179 [http-nio-8083-exec-3] org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
[DEBUG] 2016-12-21 04:41:30.179 [http-nio-8083-exec-3] org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
[DEBUG] 2016-12-21 04:41:30.187 [http-nio-8083-exec-3] org.springframework.security.web.context.HttpSessionSecurityContextRepository - No HttpSession currently exists
[DEBUG] 2016-12-21 04:41:30.187 [http-nio-8083-exec-3] org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: null. A new one will be created.
[DEBUG] 2016-12-21 04:41:30.187 [http-nio-8083-exec-3] org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
[DEBUG] 2016-12-21 04:41:30.187 [http-nio-8083-exec-3] org.springframework.security.web.header.writers.HstsHeaderWriter - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#3b41e91a
[DEBUG] 2016-12-21 04:41:30.187 [http-nio-8083-exec-3] org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
[DEBUG] 2016-12-21 04:41:30.187 [http-nio-8083-exec-3] org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/myapp/web/mainconsole'; against '/logout'
[DEBUG] 2016-12-21 04:41:30.187 [http-nio-8083-exec-3] org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 5 of 11 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
[DEBUG] 2016-12-21 04:41:30.187 [http-nio-8083-exec-3] org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
[DEBUG] 2016-12-21 04:41:30.187 [http-nio-8083-exec-3] org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
[DEBUG] 2016-12-21 04:41:30.187 [http-nio-8083-exec-3] org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
[DEBUG] 2016-12-21 04:41:30.188 [http-nio-8083-exec-3] org.springframework.security.web.authentication.AnonymousAuthenticationFilter - Populated SecurityContextHolder with anonymous token: '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] 2016-12-21 04:41:30.188 [http-nio-8083-exec-3] org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
[DEBUG] 2016-12-21 04:41:30.188 [http-nio-8083-exec-3] org.springframework.security.web.session.SessionManagementFilter - Requested session ID 2E28DB9D6699424055855E4F28D7AF9A is invalid.
[DEBUG] 2016-12-21 04:41:30.189 [http-nio-8083-exec-3] org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
[DEBUG] 2016-12-21 04:41:30.189 [http-nio-8083-exec-3] org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
[DEBUG] 2016-12-21 04:41:30.189 [http-nio-8083-exec-3] org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/myapp/web/mainconsole'; against '/myapp/api/**'
[DEBUG] 2016-12-21 04:41:30.189 [http-nio-8083-exec-3] org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Public object - authentication not attempted
[TRACE] 2016-12-21 04:41:30.189 [http-nio-8083-exec-3] org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext - Publishing event in org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#13330ac6: org.springframework.security.access.event.PublicInvocationEvent[source=FilterInvocation: URL: /myapp/web/MainConsole]
[DEBUG] 2016-12-21 04:41:30.189 [http-nio-8083-exec-3] org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'delegatingApplicationListener'
[DEBUG] 2016-12-21 04:41:30.190 [http-nio-8083-exec-3] org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole reached end of additional filter chain; proceeding with original chain
[TRACE] 2016-12-21 04:41:30.190 [http-nio-8083-exec-3] org.springframework.web.servlet.DispatcherServlet - Bound request context to thread: SecurityContextHolderAwareRequestWrapper[ org.springframework.security.web.context.HttpSessionSecurityContextRepository$Servlet3SaveToSessionRequestWrapper#1274a368]
[DEBUG] 2016-12-21 04:41:30.190 [http-nio-8083-exec-3] org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'dispatcherServlet' processing GET request for [/myapp/web/MainConsole]
[TRACE] 2016-12-21 04:41:30.190 [http-nio-8083-exec-3] org.springframework.web.servlet.DispatcherServlet - Testing handler map [org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#219e6d9f] in DispatcherServlet with name 'dispatcherServlet'
[TRACE] 2016-12-21 04:41:30.190 [http-nio-8083-exec-3] org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - No handler mapping found for [/myapp/web/MainConsole]
[TRACE] 2016-12-21 04:41:30.190 [http-nio-8083-exec-3] org.springframework.web.servlet.DispatcherServlet - Testing handler map [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#5afb11fb] in DispatcherServlet with name 'dispatcherServlet'
[DEBUG] 2016-12-21 04:41:30.190 [http-nio-8083-exec-3] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Looking up handler method for path /myapp/web/MainConsole
[TRACE] 2016-12-21 04:41:30.191 [http-nio-8083-exec-3] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Found 1 matching mapping(s) for [/myapp/web/MainConsole] : [{[/myapp/web/MainConsole]}]
[DEBUG] 2016-12-21 04:41:30.191 [http-nio-8083-exec-3] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Returning handler method [public java.lang.String com.myapp.core.controllers.web.MainConsole.showMainConsole()]
[DEBUG] 2016-12-21 04:41:30.191 [http-nio-8083-exec-3] org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'mainConsole'
[TRACE] 2016-12-21 04:41:30.191 [http-nio-8083-exec-3] org.springframework.web.servlet.DispatcherServlet - Testing handler adapter [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#718cb880]
[DEBUG] 2016-12-21 04:41:30.191 [http-nio-8083-exec-3] org.springframework.web.servlet.DispatcherServlet - Last-Modified value for [/myapp/web/MainConsole] is: -1
[TRACE] 2016-12-21 04:41:30.193 [http-nio-8083-exec-3] org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod - Invoking [MainConsole.showMainConsole] method with arguments []
[TRACE] 2016-12-21 04:41:30.194 [http-nio-8083-exec-3] org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod - Method [showMainConsole] returned [home]
[DEBUG] 2016-12-21 04:41:30.230 [http-nio-8083-exec-3] org.springframework.web.servlet.view.ContentNegotiatingViewResolver - Requested media types are [text/html, application/xhtml+xml, image/webp, application/xml;q=0.9, */*;q=0.8] based on Accept header types and producible media types [*/*])
[DEBUG] 2016-12-21 04:41:30.230 [http-nio-8083-exec-3] org.springframework.web.servlet.view.BeanNameViewResolver - No matching bean found for view name 'home'
Then, I swaped the order on "httpbasic" and "formlogin" and re-executed "http:/ /localhost:8083/myapp/web/MainConsole". Now, the correct filter - UsernamePasswordAuthenticationFilter - gets called. BUt,
the "api" hits aren't working now.
[DEBUG] 2016-12-21 04:52:56.357 org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
[DEBUG] 2016-12-21 04:52:56.383 org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
[DEBUG] 2016-12-21 04:52:56.409 org.springframework.security.web.context.HttpSessionSecurityContextRepository - No HttpSession currently exists
[DEBUG] 2016-12-21 04:52:56.410 org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: null. A new one will be created.
[DEBUG] 2016-12-21 04:52:56.514 org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
[DEBUG] 2016-12-21 04:52:56.515 org.springframework.security.web.header.writers.HstsHeaderWriter - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#32c4de26
[DEBUG] 2016-12-21 04:52:56.515 org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 4 of 12 in additional filter chain; firing Filter: 'CsrfFilter'
[DEBUG] 2016-12-21 04:52:56.567 org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 5 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
[DEBUG] 2016-12-21 04:52:56.567 org.springframework.security.web.util.matcher.AntPathRequestMatcher - Request 'GET /myapp/web/mainconsole' doesn't match 'POST /myapp/logout
[DEBUG] 2016-12-21 04:52:56.567 org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 6 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
[DEBUG] 2016-12-21 04:52:56.567 org.springframework.security.web.util.matcher.AntPathRequestMatcher - Request 'GET /myapp/web/mainconsole' doesn't match 'POST /myapp/login
[DEBUG] 2016-12-21 04:52:56.567 org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 7 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
[DEBUG] 2016-12-21 04:52:56.568 org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 8 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
[DEBUG] 2016-12-21 04:52:56.623 org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
[DEBUG] 2016-12-21 04:52:56.702 org.springframework.security.web.authentication.AnonymousAuthenticationFilter - Populated SecurityContextHolder with anonymous token: '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] 2016-12-21 04:52:56.703 org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter'
[DEBUG] 2016-12-21 04:52:56.703 org.springframework.security.web.session.SessionManagementFilter - Requested session ID 2E28DB9D6699424055855E4F28D7AF9A is invalid.
[DEBUG] 2016-12-21 04:52:56.703 org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
[DEBUG] 2016-12-21 04:52:56.703 org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
[DEBUG] 2016-12-21 04:52:56.728 org.springframework.security.web.util.matcher.AntPathRequestMatcher - Request 'GET /myapp/web/mainconsole' doesn't match 'POST /myapp/logout
[DEBUG] 2016-12-21 04:52:56.728 org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/myapp/web/mainconsole'; against '/myapp/web/**'
[DEBUG] 2016-12-21 04:52:56.729 org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Secure object: FilterInvocation: URL: /myapp/web/MainConsole; Attributes: [authenticated]
[DEBUG] 2016-12-21 04:52:56.729 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] 2016-12-21 04:52:56.930 org.springframework.security.access.vote.AffirmativeBased - Voter: org.springframework.security.web.access.expression.WebExpressionVoter#9d78e5c, returned: -1
[TRACE] 2016-12-21 04:52:56.931 org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext - Publishing event in org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#13330ac6: org.springframework.security.access.event.AuthorizationFailureEvent[source=FilterInvocation: URL: /myapp/web/MainConsole]
[DEBUG] 2016-12-21 04:52:56.931 org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'delegatingApplicationListener'
[DEBUG] 2016-12-21 04:52:56.932 org.springframework.security.web.access.ExceptionTranslationFilter - Access is denied (user is anonymous); redirecting to authentication entry point
Why is httpsbasic is ALWAYS taking first precedence, regardless of a URL pattern that matches for formlogin?
Because you set the api order to 1, so it will always in API filter chain.Change the api config to this. This will match the request path first.
http.antMatcher("/myapp/api/**")
.csrf().disable().authorizeRequests()
.antMatchers("/**").authenticated().and() // Permit access for all to login REST service
.httpBasic()
.authenticationEntryPoint(new MyAuthenticationFailurePoint());

An Authentication object was not found in the SecurityContext (Spring 2.5.2)

I'm using Spring 2.5.2 and same version of spring security.
Issue is, I login through the application and clears my browser cookies and refreshes the page application is redirected to the login page but at the back it throws following exception
DEBUG ExceptionTranslationFilter - Authentication exception occurred; redirecting to authentication entry point
org.springframework.security.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
at org.springframework.security.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:342)
at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:254)
at org.springframework.security.intercept.web.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:106)
at org.springframework.security.intercept.web.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:390)
at org.springframework.security.ui.SessionFixationProtectionFilter.doFilterHttp(SessionFixationProtectionFilter.java:52)
at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53)
at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:390)
Continue till at java.lang.Thread.run(Unknown Source)
After this exception application is redirected to the login page & after entering the login credentials
I have to click my login button twice to enter into the application.
After the first click console shows
DEBUG CptLogger - com.capgent.cpt.server.services.auth.LoginAuthenticationProvider Method invoked : additionalAuthenticationChecks isAuthenticated ? :false
DEBUG XmlWebApplicationContext - Publishing event in context [org.springframework.web.context.support.XmlWebApplicationContext#1d0d124]: org.springframework.security.event.authentication.AuthenticationSuccessEvent[source=org.springframework.security.providers.UsernamePasswordAuthenticationToken#862413dc: Principal: com.capgent.cpt.server.services.auth.UserDetailsContainer#bc1ebd; Password: [PROTECTED]; Authenticated: true; Details: org.springframework.security.ui.WebAuthenticationDetails#0: RemoteIpAddress: 127.0.0.1; SessionId: 6693D3BCE880D6339D9D149F44637952; Granted Authorities: ROLE_ADMIN]
DEBUG AuthenticationProcessingFilter - Authentication success: org.springframework.security.providers.UsernamePasswordAuthenticationToken#862413dc: Principal: com.capgent.cpt.server.services.auth.UserDetailsContainer#bc1ebd; Password: [PROTECTED]; Authenticated: true; Details: org.springframework.security.ui.WebAuthenticationDetails#0: RemoteIpAddress: 127.0.0.1; SessionId: 6693D3BCE880D6339D9D149F44637952; Granted Authorities: ROLE_ADMIN
DEBUG AuthenticationProcessingFilter - Updated SecurityContextHolder to contain the following Authentication: 'org.springframework.security.providers.UsernamePasswordAuthenticationToken#862413dc: Principal: com.capgent.cpt.server.services.auth.UserDetailsContainer#bc1ebd; Password: [PROTECTED]; Authenticated: true; Details: org.springframework.security.ui.WebAuthenticationDetails#0: RemoteIpAddress: 127.0.0.1; SessionId: 6693D3BCE880D6339D9D149F44637952; Granted Authorities: ROLE_ADMIN'
DEBUG SessionUtils - Invalidating session with Id '6693D3BCE880D6339D9D149F44637952' and migrating attributes.
DEBUG SessionUtils - Started new session: E772A0D1441C079B2ACD3698F68AF63C
DEBUG AuthenticationProcessingFilter - Redirecting to target URL from HTTP Session (or default): http://localhost:8090/resources/com.capgent.cpt.Main/Main.jsp
DEBUG omTokenBasedRemembermeServices - Did not send remember-me cookie (principal did not set parameter '_spring_security_remember_me')
DEBUG omTokenBasedRemembermeServices - Remember-me login not requested.
DEBUG XmlWebApplicationContext - Publishing event in context [org.springframework.web.context.support.XmlWebApplicationContext#1d0d124]: org.springframework.security.event.authentication.InteractiveAuthenticationSuccessEvent[source=org.springframework.security.providers.UsernamePasswordAuthenticationToken#862413dc: Principal: com.capgent.cpt.server.services.auth.UserDetailsContainer#bc1ebd; Password: [PROTECTED]; Authenticated: true; Details: org.springframework.security.ui.WebAuthenticationDetails#0: RemoteIpAddress: 127.0.0.1; SessionId: 6693D3BCE880D6339D9D149F44637952; Granted Authorities: ROLE_ADMIN]
DEBUG essionContextIntegrationFilter - SecurityContext stored to HttpSession: 'org.springframework.security.context.SecurityContextImpl#862413dc: Authentication: org.springframework.security.providers.UsernamePasswordAuthenticationToken#862413dc: Principal: com.capgent.cpt.server.services.auth.UserDetailsContainer#bc1ebd; Password: [PROTECTED]; Authenticated: true; Details: org.springframework.security.ui.WebAuthenticationDetails#0: RemoteIpAddress: 127.0.0.1; SessionId: 6693D3BCE880D6339D9D149F44637952; Granted Authorities: ROLE_ADMIN'
DEBUG essionContextIntegrationFilter - SecurityContextHolder now cleared, as request processing completed
DEBUG RequestContextFilter - Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade#1d03700
DEBUG nsactionSynchronizationManager - Removed value [org.springframework.orm.hibernate3.SessionHolder#1c9dea3] for key [org.hibernate.impl.SessionFactoryImpl#42c282] from thread [http-8090-Processor25]
DEBUG OpenSessionInViewFilter - Closing single Hibernate Session in OpenSessionInViewFilter
DEBUG SessionFactoryUtils - Closing Hibernate Session
DEBUG ConnectionManager - releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]
DEBUG ConnectionManager - transaction completed on session with on_close connection release mode; be sure to close the session to release JDBC resources!
DEBUG OpenSessionInViewFilter - Using SessionFactory 'cptSessionFactory' for OpenSessionInViewFilter
DEBUG DefaultListableBeanFactory - Returning cached instance of singleton bean 'cptSessionFactory'
DEBUG OpenSessionInViewFilter - Opening single Hibernate Session in OpenSessionInViewFilter
DEBUG SessionFactoryUtils - Opening Hibernate Session
DEBUG SessionImpl - opened session at timestamp: 13938439638
DEBUG nsactionSynchronizationManager - Bound value [org.springframework.orm.hibernate3.SessionHolder#862557] for key [org.hibernate.impl.SessionFactoryImpl#42c282] to thread [http-8090-Processor25]
DEBUG RequestContextFilter - Bound request context to thread: org.apache.catalina.connector.RequestFacade#1d03700
DEBUG FilterChainProxy - Converted URL to lowercase, from: '/com.capgent.cpt.main/main.jsp'; to: '/com.capgent.cpt.main/main.jsp'
DEBUG FilterChainProxy - Candidate is: '/com.capgent.cpt.main/main.jsp'; pattern is /ssoerror.html*; matched=false
DEBUG FilterChainProxy - Converted URL to lowercase, from: '/com.capgent.cpt.main/main.jsp'; to: '/com.capgent.cpt.main/main.jsp'
DEBUG FilterChainProxy - Candidate is: '/com.capgent.cpt.main/main.jsp'; pattern is /; matched=true
DEBUG FilterChainProxy - /com.capgent.cpt.Main/Main.jsp at position 1 of 10 in additional filter chain; firing Filter: 'org.springframework.security.context.HttpSessionContextIntegrationFilter[ order=200; ]'
DEBUG essionContextIntegrationFilter - Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT to associate with SecurityContextHolder: 'org.springframework.security.context.SecurityContextImpl#862413dc: Authentication: org.springframework.security.providers.UsernamePasswordAuthenticationToken#862413dc: Principal: com.capgent.cpt.server.services.auth.UserDetailsContainer#bc1ebd; Password: [PROTECTED]; Authenticated: true; Details: org.springframework.security.ui.WebAuthenticationDetails#0: RemoteIpAddress: 127.0.0.1; SessionId: 6693D3BCE880D6339D9D149F44637952; Granted Authorities: ROLE_ADMIN'
DEBUG FilterChainProxy - /com.capgent.cpt.Main/Main.jsp at position 2 of 10 in additional filter chain; firing Filter: 'com.capgent.cpt.server.services.auth.CantrexSsoProcessingFilter[ order=600; ]'
DEBUG FilterChainProxy - /com.capgent.cpt.Main/Main.jsp at position 3 of 10 in additional filter chain; firing Filter: 'com.capgent.cpt.server.services.auth.DnbiSsoProcessingFilter[ order=600; ]'
DEBUG FilterChainProxy - /com.capgent.cpt.Main/Main.jsp at position 4 of 10 in additional filter chain; firing Filter: 'com.capgent.cpt.server.services.auth.OpenIdAuthenticationProcessingFilter[ order=800; ]'
DEBUG FilterChainProxy - /com.capgent.cpt.Main/Main.jsp at position 5 of 10 in additional filter chain; firing Filter: 'org.springframework.security.ui.webapp.AuthenticationProcessingFilter[ order=700; ]'
DEBUG FilterChainProxy - /com.capgent.cpt.Main/Main.jsp at position 6 of 10 in additional filter chain; firing Filter: 'org.springframework.security.wrapper.SecurityContextHolderAwareRequestFilter[ order=1100; ]'
DEBUG SavedRequest - pathInfo: both null (property equals)
DEBUG SavedRequest - queryString: both null (property equals)
DEBUG SavedRequest - requestURI: arg1=/resources/com.capgent.cpt.Main/Main.jsp; arg2=/resources/com.capgent.cpt.Main/Main.jsp (property equals)
DEBUG SavedRequest - serverPort: arg1=8090; arg2=8090 (property equals)
DEBUG SavedRequest - requestURL: arg1=http://localhost:8090/resources/com.capgent.cpt.Main/Main.jsp; arg2=http://localhost:8090/resources/com.capgent.cpt.Main/Main.jsp (property equals)
DEBUG SavedRequest - scheme: arg1=http; arg2=http (property equals)
DEBUG SavedRequest - serverName: arg1=localhost; arg2=localhost (property equals)
DEBUG SavedRequest - contextPath: arg1=/resources; arg2=/resources (property equals)
DEBUG SavedRequest - servletPath: arg1=/com.capgent.cpt.Main/Main.jsp; arg2=/com.capgent.cpt.Main/Main.jsp (property equals)
DEBUG SavedRequestAwareWrapper - Wrapper replaced; SavedRequest was: SavedRequest[http://localhost:8090/resources/com.capgent.cpt.Main/Main.jsp]
DEBUG FilterChainProxy - /com.capgent.cpt.Main/Main.jsp at position 7 of 10 in additional filter chain; firing Filter: 'org.springframework.security.ui.rememberme.RememberMeProcessingFilter[ order=1200; ]'
DEBUG RememberMeProcessingFilter - SecurityContextHolder not populated with remember-me token, as it already contained: 'org.springframework.security.providers.UsernamePasswordAuthenticationToken#862413dc: Principal: com.capgent.cpt.server.services.auth.UserDetailsContainer#bc1ebd; Password: [PROTECTED]; Authenticated: true; Details: org.springframework.security.ui.WebAuthenticationDetails#0: RemoteIpAddress: 127.0.0.1; SessionId: 6693D3BCE880D6339D9D149F44637952; Granted Authorities: ROLE_ADMIN'
DEBUG FilterChainProxy - /com.capgent.cpt.Main/Main.jsp at position 8 of 10 in additional filter chain; firing Filter: 'org.springframework.security.ui.ExceptionTranslationFilter[ order=1400; ]'
DEBUG FilterChainProxy - /com.capgent.cpt.Main/Main.jsp at position 9 of 10 in additional filter chain; firing Filter: 'org.springframework.security.ui.SessionFixationProtectionFilter[ order=1600; ]'
DEBUG FilterChainProxy - /com.capgent.cpt.Main/Main.jsp at position 10 of 10 in additional filter chain; firing Filter: 'org.springframework.security.intercept.web.FilterSecurityInterceptor#11ca33b'
DEBUG lterInvocationDefinitionSource - Converted URL to lowercase, from: '/com.capgent.cpt.main/main.jsp'; to: '/com.capgent.cpt.main/main.jsp'
DEBUG lterInvocationDefinitionSource - Candidate is: '/com.capgent.cpt.main/main.jsp'; pattern is //*main.jsp; matched=true
DEBUG AbstractSecurityInterceptor - Secure object: FilterInvocation: URL: /com.capgent.cpt.Main/Main.jsp; ConfigAttributes: [ROLE_ADMIN]
DEBUG AbstractSecurityInterceptor - Previously Authenticated: org.springframework.security.providers.UsernamePasswordAuthenticationToken#862413dc: Principal: com.capgent.cpt.server.services.auth.UserDetailsContainer#bc1ebd; Password: [PROTECTED]; Authenticated: true; Details: org.springframework.security.ui.WebAuthenticationDetails#0: RemoteIpAddress: 127.0.0.1; SessionId: 6693D3BCE880D6339D9D149F44637952; Granted Authorities: ROLE_ADMIN
DEBUG AbstractSecurityInterceptor - Authorization successful
DEBUG XmlWebApplicationContext - Publishing event in context [org.springframework.web.context.support.XmlWebApplicationContext#1d0d124]: org.springframework.security.event.authorization.AuthorizedEvent[source=FilterInvocation: URL: /com.capgent.cpt.Main/Main.jsp]
DEBUG AbstractSecurityInterceptor - RunAsManager did not change Authentication object
DEBUG FilterChainProxy - /com.capgent.cpt.Main/Main.jsp reached end of additional filter chain; proceeding with original chain
DEBUG JspServlet - JspEngine --> /com.capgent.cpt.Main/Main.jsp
DEBUG JspServlet - ServletPath: /com.capgent.cpt.Main/Main.jsp
DEBUG JspServlet - PathInfo: null
DEBUG JspServlet - RealPath: D:\springworkspace.metadata.plugins\org.eclipse.wst.server.core\tmp3\wtpwebapps\capgentspring\com.capgent.cpt.Main\Main.jsp
DEBUG JspServlet - RequestURI: /resources/com.capgent.cpt.Main/Main.jsp
DEBUG JspServlet - QueryString: null
"Issue is, I login through the application and clears my browser cookies and refreshes the page application is redirected to the login page"
Yes.It is the Normal behavior. Because a new session will be started from there since the old session was invalidated/closed.
"but at the back it throws following exception"
Yes.It will, because it tries to revalidate the user info/session when you refresh the page.Since you have already cleared the cookies, it will fail.
Setting the <form-login login-page="/Login.jsp" authentication-failure-url="/LoginHandler.jsp" always-use-default-target="true" default-target-url="/LoginHandler.jsp"/>
has solved my issue earlier the value was alway-use-default-target="false"

Spring Security JavaConfig with HTTP Basic and JSR-250: 403 Forbidden

How the Configuration should look like when using #RolesAllowed Annotation?
I don't need any auth at my webpage as there's no login or anything else. Only the admin panel should have an http basic auth.
This is my current code:
public class WebAppInitializer extends AbstractSecurityWebApplicationInitializer {
#Override
public void beforeSpringSecurityFilterChain(ServletContext servletContext) {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.getEnvironment().setDefaultProfiles("production");
rootContext.scan("com.xxx.config");
container.addListener(new ContextLoaderListener(rootContext));
ServletRegistration.Dynamic servlet = container.addServlet("DispatcherServlet", DispatcherServlet.class);
servlet.setInitParameter("contextConfigLocation", "");
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
FilterRegistration charEncodingfilterReg = container.addFilter("CharacterEncodingFilter", CharacterEncodingFilter.class);
charEncodingfilterReg.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
charEncodingfilterReg.setInitParameter("encoding", "UTF-8");
charEncodingfilterReg.setInitParameter("forceEncoding", "true");
}
}
#Controller
#RequestMapping("admin")
#RolesAllowed("admin")
public class AdminController {
// ...
}
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private Environment env;
private static final Logger log = LoggerFactory.getLogger(SecurityConfig.class);
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().realmName(env.getProperty("adminRealm"));
}
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
// Output: DEBUG SecurityConfig - Register credentials for roles user, admin: admin:admin
log.debug("Register credentials for roles user, admin: " + env.getProperty("adminUsername") + ":" + env.getProperty("adminPassword"));
auth.inMemoryAuthentication().withUser(env.getProperty("adminUsername")).password(env.getProperty("adminPassword")).roles("user", "admin");
}
}
But after the login with the correct credentials I'm just getting a HTTP 403.
Log while requesting the admin panel:
DEBUG AnonymousAuthenticationFilter - SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken#80a4fdc5: Principal: org.springframework.security.core.userdetails.User#586034f: Username: admin; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_admin,ROLE_user; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#12afc: RemoteIpAddress: 127.0.0.1; SessionId: 5973DDB69FFF44B3B9AD6077DFD7B1ED; Granted Authorities: ROLE_admin, ROLE_user'
DEBUG FilterChainProxy - /resources/webjars/fancybox/jquery.fancybox.css at position 10 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
DEBUG FilterChainProxy - /resources/webjars/fancybox/jquery.fancybox.css at position 11 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
DEBUG FilterChainProxy - /resources/webjars/fancybox/jquery.fancybox.css reached end of additional filter chain; proceeding with original chain
DEBUG DispatcherServlet - DispatcherServlet with name 'DispatcherServlet' processing GET request for [/resources/webjars/fancybox/jquery.fancybox.css]
DEBUG DispatcherServlet - Taking snapshot of request attributes before include
DEBUG RequestMappingHandlerMapping - Looking up handler method for path /resources/webjars/fancybox/jquery.fancybox.css
DEBUG RequestMappingHandlerMapping - Did not find handler method for [/resources/webjars/fancybox/jquery.fancybox.css]
DEBUG SimpleUrlHandlerMapping - Matching patterns for request [/resources/webjars/fancybox/jquery.fancybox.css] are [/resources/**]
DEBUG SimpleUrlHandlerMapping - URI Template variables for request [/resources/webjars/fancybox/jquery.fancybox.css] are {}
DEBUG SimpleUrlHandlerMapping - Mapping [/resources/webjars/fancybox/jquery.fancybox.css] to HandlerExecutionChain with handler [org.springframework.web.servlet.resource.ResourceHttpRequestHandler#2f096210] and 1 interceptor
DEBUG DispatcherServlet - Last-Modified value for [/resources/webjars/fancybox/jquery.fancybox.css] is: -1
DEBUG ResourceHttpRequestHandler - Trying relative path [webjars/fancybox/jquery.fancybox.css] against base location: ServletContext resource [/resources/**]
DEBUG ResourceHttpRequestHandler - Found matching resource: ServletContext resource [/resources/webjars/fancybox/jquery.fancybox.css]
DEBUG ResourceHttpRequestHandler - Determined media type 'text/css' for ServletContext resource [/resources/webjars/fancybox/jquery.fancybox.css]
DEBUG DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'DispatcherServlet': assuming HandlerAdapter completed request handling
DEBUG DispatcherServlet - Restoring snapshot of request attributes after include
DEBUG DispatcherServlet - Removing attribute [org.springframework.web.servlet.HandlerMapping.introspectTypeLevelMapping] after include
DEBUG DispatcherServlet - Removing attribute [org.springframework.web.servlet.DispatcherServlet.FLASH_MAP_MANAGER] after include
DEBUG DispatcherServlet - Removing attribute [org.springframework.web.servlet.DispatcherServlet.THEME_SOURCE] after include
DEBUG DispatcherServlet - Removing attribute [org.springframework.web.servlet.DispatcherServlet.THEME_RESOLVER] after include
DEBUG DispatcherServlet - Removing attribute [org.springframework.web.servlet.DispatcherServlet.CONTEXT] after include
DEBUG DispatcherServlet - Removing attribute [org.springframework.web.servlet.HandlerMapping.pathWithinHandlerMapping] after include
DEBUG DispatcherServlet - Removing attribute [org.springframework.web.servlet.DispatcherServlet.OUTPUT_FLASH_MAP] after include
DEBUG DispatcherServlet - Removing attribute [org.springframework.web.servlet.HandlerMapping.bestMatchingPattern] after include
DEBUG DispatcherServlet - Removing attribute [org.springframework.web.servlet.DispatcherServlet.LOCALE_RESOLVER] after include
DEBUG DispatcherServlet - Successfully completed request
DEBUG ExceptionTranslationFilter - Chain processed normally
DEBUG ProcessorDecorator - Applying processor: ro.isdc.wro.extensions.processor.css.LessCssProcessor#2377a016
DEBUG ProcessorDecorator - Applying processor: ro.isdc.wro.extensions.processor.css.LessCssProcessor#2377a016
DEBUG ProcessorDecorator - Applying processor: ro.isdc.wro.extensions.processor.css.LessCssProcessor#2377a016
DEBUG ProcessorDecorator - Applying processor: ro.isdc.wro.extensions.processor.css.LessCssProcessor#2377a016
DEBUG ProcessorDecorator - Applying processor: ro.isdc.wro.extensions.processor.css.LessCssProcessor#2377a016
DEBUG ProcessorDecorator - Applying processor: ro.isdc.wro.extensions.processor.css.LessCssProcessor#2377a016
DEBUG ProcessorDecorator - Skipping processor: ro.isdc.wro.extensions.processor.css.LessCssProcessor#2377a016
DEBUG BenchmarkProcessorDecorator - StopWatch '': running time (millis) = 0
-----------------------------------------
ms % Task name
-----------------------------------------
00000 � Using ro.isdc.wro.extensions.processor.css.LessCssProcessor#2377a016
DEBUG ProcessorDecorator - Applying processor: ro.isdc.wro.model.resource.processor.impl.css.CssUrlRewritingProcessor#76ec1185
...much wro4j stuff...
DEBUG BenchmarkProcessorDecorator - StopWatch '': running time (millis) = 2770
-----------------------------------------
ms % Task name
-----------------------------------------
02770 100% Using ro.isdc.wro.model.resource.processor.impl.css.JawrCssMinifierProcessor#2c8e5aa6
DEBUG DefaultSynchronizedCacheStrategyDecorator - found content: .clearfix{*zoom:1}.clearfix...
DEBUG DefaultSynchronizedCacheStrategyDecorator - Content to fingerprint: [.clearfix{*zoom:1}.clearfix...]
DEBUG AbstractDigesterHashStrategy - SHA1HashStrategy hash: 51eda04c354d73243fa387841c9d888bbeb4a201
DEBUG DefaultSynchronizedCacheStrategyDecorator - computed entry: hash: 51eda04c354d73243fa387841c9d888bbeb4a201
DEBUG ResourceBundleProcessor - ETag hash detected: "51eda04c354d73243fa387841c9d888bbeb4a201". Sending 304 status code
DEBUG WroFilter - Disable Cache is true. Destroying model...
DEBUG DefaultWroModelFactoryDecorator - Destroy model
DEBUG DefaultResourceAuthorizationManager - clear.
DEBUG DefaultResourceAuthorizationManager - clear.
DEBUG ExceptionTranslationFilter - Chain processed normally
DEBUG SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
DEBUG FilterChainProxy - /resources/img/logo.png at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
DEBUG FilterChainProxy - /resources/img/logo.png at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
DEBUG HttpSessionSecurityContextRepository - Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'org.springframework.security.core.context.SecurityContextImpl#80a4fdc5: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#80a4fdc5: Principal: org.springframework.security.core.userdetails.User#586034f: Username: admin; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_admin,ROLE_user; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#12afc: RemoteIpAddress: 127.0.0.1; SessionId: 5973DDB69FFF44B3B9AD6077DFD7B1ED; Granted Authorities: ROLE_admin, ROLE_user'
DEBUG FilterChainProxy - /resources/img/logo.png at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
DEBUG HstsHeaderWriter - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#51879f03
DEBUG FilterChainProxy - /resources/img/logo.png at position 4 of 11 in additional filter chain; firing Filter: 'CsrfFilter'
DEBUG FilterChainProxy - /resources/img/logo.png at position 5 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
DEBUG AntPathRequestMatcher - Checking match of request : '/resources/img/logo.png'; against '/logout'
DEBUG FilterChainProxy - /resources/img/logo.png at position 6 of 11 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
DEBUG FilterChainProxy - /resources/img/logo.png at position 7 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
DEBUG FilterChainProxy - /resources/img/logo.png at position 8 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
DEBUG FilterChainProxy - /resources/img/logo.png at position 9 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
DEBUG AnonymousAuthenticationFilter - SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken#80a4fdc5: Principal: org.springframework.security.core.userdetails.User#586034f: Username: admin; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_admin,ROLE_user; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#12afc: RemoteIpAddress: 127.0.0.1; SessionId: 5973DDB69FFF44B3B9AD6077DFD7B1ED; Granted Authorities: ROLE_admin, ROLE_user'
DEBUG FilterChainProxy - /resources/img/logo.png at position 10 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
DEBUG FilterChainProxy - /resources/img/logo.png at position 11 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
DEBUG FilterChainProxy - /resources/img/logo.png reached end of additional filter chain; proceeding with original chain
DEBUG DispatcherServlet - DispatcherServlet with name 'DispatcherServlet' processing GET request for [/resources/img/logo.png]
DEBUG RequestMappingHandlerMapping - Looking up handler method for path /resources/img/logo.png
DEBUG RequestMappingHandlerMapping - Did not find handler method for [/resources/img/logo.png]
DEBUG SimpleUrlHandlerMapping - Matching patterns for request [/resources/img/logo.png] are [/resources/**]
DEBUG SimpleUrlHandlerMapping - URI Template variables for request [/resources/img/logo.png] are {}
DEBUG SimpleUrlHandlerMapping - Mapping [/resources/img/logo.png] to HandlerExecutionChain with handler [org.springframework.web.servlet.resource.ResourceHttpRequestHandler#2f096210] and 1 interceptor
DEBUG DispatcherServlet - Last-Modified value for [/resources/img/logo.png] is: -1
DEBUG ResourceHttpRequestHandler - Trying relative path [img/logo.png] against base location: ServletContext resource [/resources/**]
DEBUG ResourceHttpRequestHandler - Found matching resource: ServletContext resource [/resources/img/logo.png]
DEBUG ResourceHttpRequestHandler - Determined media type 'image/png' for ServletContext resource [/resources/img/logo.png]
DEBUG DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'DispatcherServlet': assuming HandlerAdapter completed request handling
DEBUG DispatcherServlet - Successfully completed request
DEBUG ExceptionTranslationFilter - Chain processed normally
DEBUG SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
DEBUG FilterChainProxy - /resources/img/eagle.png at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
DEBUG FilterChainProxy - /resources/img/eagle.png at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
DEBUG HttpSessionSecurityContextRepository - Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'org.springframework.security.core.context.SecurityContextImpl#80a4fdc5: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#80a4fdc5: Principal: org.springframework.security.core.userdetails.User#586034f: Username: admin; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_admin,ROLE_user; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#12afc: RemoteIpAddress: 127.0.0.1; SessionId: 5973DDB69FFF44B3B9AD6077DFD7B1ED; Granted Authorities: ROLE_admin, ROLE_user'
DEBUG FilterChainProxy - /resources/img/eagle.png at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
DEBUG HstsHeaderWriter - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#51879f03
DEBUG FilterChainProxy - /resources/img/eagle.png at position 4 of 11 in additional filter chain; firing Filter: 'CsrfFilter'
DEBUG FilterChainProxy - /resources/img/eagle.png at position 5 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
DEBUG AntPathRequestMatcher - Checking match of request : '/resources/img/eagle.png'; against '/logout'
DEBUG FilterChainProxy - /resources/img/eagle.png at position 6 of 11 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
DEBUG FilterChainProxy - /resources/img/eagle.png at position 7 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
DEBUG FilterChainProxy - /resources/img/eagle.png at position 8 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
DEBUG FilterChainProxy - /resources/img/eagle.png at position 9 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
DEBUG AnonymousAuthenticationFilter - SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken#80a4fdc5: Principal: org.springframework.security.core.userdetails.User#586034f: Username: admin; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_admin,ROLE_user; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#12afc: RemoteIpAddress: 127.0.0.1; SessionId: 5973DDB69FFF44B3B9AD6077DFD7B1ED; Granted Authorities: ROLE_admin, ROLE_user'
DEBUG FilterChainProxy - /resources/img/eagle.png at position 10 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
DEBUG FilterChainProxy - /resources/img/eagle.png at position 11 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
DEBUG FilterChainProxy - /resources/img/eagle.png reached end of additional filter chain; proceeding with original chain
DEBUG DispatcherServlet - DispatcherServlet with name 'DispatcherServlet' processing GET request for [/resources/img/eagle.png]
DEBUG RequestMappingHandlerMapping - Looking up handler method for path /resources/img/eagle.png
DEBUG FilterChainProxy - /resources/webjars/font/fontawesome-webfont.woff?v=3.2.1 at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
DEBUG FilterChainProxy - /resources/webjars/font/fontawesome-webfont.woff?v=3.2.1 at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
DEBUG HttpSessionSecurityContextRepository - Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'org.springframework.security.core.context.SecurityContextImpl#80a4fdc5: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#80a4fdc5: Principal: org.springframework.security.core.userdetails.User#586034f: Username: admin; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_admin,ROLE_user; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#12afc: RemoteIpAddress: 127.0.0.1; SessionId: 5973DDB69FFF44B3B9AD6077DFD7B1ED; Granted Authorities: ROLE_admin, ROLE_user'
DEBUG FilterChainProxy - /resources/webjars/font/fontawesome-webfont.woff?v=3.2.1 at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
DEBUG HstsHeaderWriter - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#51879f03
DEBUG FilterChainProxy - /resources/webjars/font/fontawesome-webfont.woff?v=3.2.1 at position 4 of 11 in additional filter chain; firing Filter: 'CsrfFilter'
DEBUG FilterChainProxy - /resources/webjars/font/fontawesome-webfont.woff?v=3.2.1 at position 5 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
DEBUG AntPathRequestMatcher - Checking match of request : '/resources/webjars/font/fontawesome-webfont.woff'; against '/logout'
DEBUG FilterChainProxy - /resources/webjars/font/fontawesome-webfont.woff?v=3.2.1 at position 6 of 11 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
DEBUG FilterChainProxy - /resources/webjars/font/fontawesome-webfont.woff?v=3.2.1 at position 7 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
DEBUG FilterChainProxy - /resources/webjars/font/fontawesome-webfont.woff?v=3.2.1 at position 8 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
DEBUG RequestMappingHandlerMapping - Did not find handler method for [/resources/img/eagle.png]
DEBUG FilterChainProxy - /resources/webjars/font/fontawesome-webfont.woff?v=3.2.1 at position 9 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
DEBUG SimpleUrlHandlerMapping - Matching patterns for request [/resources/img/eagle.png] are [/resources/**]
DEBUG AnonymousAuthenticationFilter - SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken#80a4fdc5: Principal: org.springframework.security.core.userdetails.User#586034f: Username: admin; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_admin,ROLE_user; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#12afc: RemoteIpAddress: 127.0.0.1; SessionId: 5973DDB69FFF44B3B9AD6077DFD7B1ED; Granted Authorities: ROLE_admin, ROLE_user'
DEBUG SimpleUrlHandlerMapping - URI Template variables for request [/resources/img/eagle.png] are {}
DEBUG FilterChainProxy - /resources/webjars/font/fontawesome-webfont.woff?v=3.2.1 at position 10 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
DEBUG SimpleUrlHandlerMapping - Mapping [/resources/img/eagle.png] to HandlerExecutionChain with handler [org.springframework.web.servlet.resource.ResourceHttpRequestHandler#2f096210] and 1 interceptor
DEBUG FilterChainProxy - /resources/webjars/font/fontawesome-webfont.woff?v=3.2.1 at position 11 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
DEBUG DispatcherServlet - Last-Modified value for [/resources/img/eagle.png] is: -1
DEBUG FilterChainProxy - /resources/webjars/font/fontawesome-webfont.woff?v=3.2.1 reached end of additional filter chain; proceeding with original chain
DEBUG ResourceHttpRequestHandler - Trying relative path [img/eagle.png] against base location: ServletContext resource [/resources/**]
DEBUG DispatcherServlet - DispatcherServlet with name 'DispatcherServlet' processing GET request for [/resources/webjars/font/fontawesome-webfont.woff]
DEBUG ResourceHttpRequestHandler - Found matching resource: ServletContext resource [/resources/img/eagle.png]
DEBUG ResourceHttpRequestHandler - Determined media type 'image/png' for ServletContext resource [/resources/img/eagle.png]
DEBUG DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'DispatcherServlet': assuming HandlerAdapter completed request handling
DEBUG DispatcherServlet - Successfully completed request
DEBUG ExceptionTranslationFilter - Chain processed normally
DEBUG SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
DEBUG RequestMappingHandlerMapping - Looking up handler method for path /resources/webjars/font/fontawesome-webfont.woff
DEBUG RequestMappingHandlerMapping - Did not find handler method for [/resources/webjars/font/fontawesome-webfont.woff]
DEBUG SimpleUrlHandlerMapping - Matching patterns for request [/resources/webjars/font/fontawesome-webfont.woff] are [/resources/**]
DEBUG SimpleUrlHandlerMapping - URI Template variables for request [/resources/webjars/font/fontawesome-webfont.woff] are {}
DEBUG SimpleUrlHandlerMapping - Mapping [/resources/webjars/font/fontawesome-webfont.woff] to HandlerExecutionChain with handler [org.springframework.web.servlet.resource.ResourceHttpRequestHandler#2f096210] and 1 interceptor
DEBUG DispatcherServlet - Last-Modified value for [/resources/webjars/font/fontawesome-webfont.woff] is: -1
DEBUG ResourceHttpRequestHandler - Trying relative path [webjars/font/fontawesome-webfont.woff] against base location: ServletContext resource [/resources/**]
DEBUG ResourceHttpRequestHandler - Found matching resource: ServletContext resource [/resources/webjars/font/fontawesome-webfont.woff]
DEBUG ResourceHttpRequestHandler - Determined media type 'application/x-font-woff' for ServletContext resource [/resources/webjars/font/fontawesome-webfont.woff]
DEBUG DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'DispatcherServlet': assuming HandlerAdapter completed request handling
DEBUG DispatcherServlet - Successfully completed request
DEBUG ExceptionTranslationFilter - Chain processed normally
DEBUG SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
Permissions:
$ cd ~/workspace/xxxxx/target/classes && ls -l . && ls -l META-INF && ls -l META-INF/services && ls -l properties && ls -l properties/common && ls -l properties/development
insgesamt 76
drwxrwxr-x 4 danny danny 4096 Nov 12 17:57 com
-rw-rw-r-- 1 danny danny 19074 Nov 12 17:57 import.sql
-rw-rw-r-- 1 danny danny 519 Nov 14 22:16 logback.xml
drwxrwxr-x 3 danny danny 4096 Nov 12 17:57 META-INF
drwxrwxr-x 5 danny danny 4096 Nov 12 17:57 properties
-rw-rw-r-- 1 danny danny 2215 Nov 12 17:57 tiles.xml
-rw-rw-r-- 1 danny danny 2444 Nov 12 17:57 wro.xml
insgesamt 4
drwxrwxr-x 2 danny danny 4096 Nov 12 17:57 services
insgesamt 24
-rw-rw-r-- 1 danny danny 34 Nov 12 17:57 javax.servlet.ServletContainerInitializer
-rw-rw-r-- 1 danny danny 57 Nov 12 17:57 ro.isdc.wro.model.spi.ModelFactoryProvider
insgesamt 12
drwxrwxr-x 2 danny danny 4096 Nov 12 17:57 common
drwxrwxr-x 2 danny danny 4096 Nov 12 17:57 development
drwxrwxr-x 2 danny danny 4096 Nov 12 17:57 production
insgesamt 48
-rw-rw-r-- 1 danny danny 737 Nov 12 17:57 application.properties
-rw-rw-r-- 1 danny danny 57 Nov 12 17:57 hibernate.properties
-rw-rw-r-- 1 danny danny 88 Nov 12 17:57 jdbc.properties
-rw-rw-r-- 1 danny danny 125 Nov 12 17:57 wro.properties
insgesamt 48
-rw-rw-r-- 1 danny danny 142 Nov 12 17:57 application.properties
-rw-rw-r-- 1 danny danny 53 Nov 12 17:57 hibernate.properties
-rw-rw-r-- 1 danny danny 35 Nov 12 17:57 jdbc.properties
-rw-rw-r-- 1 danny danny 17 Nov 12 17:57 wro.properties
As you are using the default authentication manager your rolenames must be prefixed with "ROLE_" to be matched.

GWT Spring Security Integration (PURE GWT, NO JSP)

I´m using GWT 2.4 and Spring 3.1 and I want to secure my application with Spring Security. I was looking for a GWT-only solution without a separate JSP login page. I found only old sites using JSP to do login, so this thread could result in a solution to fully integrate GWT with Spring Security in a standard way. Anyway, if there is a reference where this has been done successfully already, this thread can be closed with a link to that reference of course.
So far here is my first approach:
applicationcontext-security.xml:
<http auto-config="false" use-expressions="true" entry-point-ref="customAuthenticationEntryPoint">
<intercept-url pattern="/ApplicationScaffold.html" access="permitAll" />
<intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
</http>
<beans:bean id="customAuthenticationEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint"
c:loginFormUrl="/ApplicationScaffold.html" />
<!-- Configure Authentication mechanism -->
<authentication-manager alias="authenticationManager">
<authentication-provider>
...
</authentication-provider>
</authentication-manager>
ApplicationScaffold.html (my application was created with Spring Roo) is my starting page containing the GWT login page.
web.xml:
<display-name>securitytest</display-name>
<description>Roo generated application</description>
<!-- Enable escaping of form submission contents -->
<context-param>
<param-name>defaultHtmlEscape</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:META-INF/spring/applicationContext*.xml</param-value>
</context-param>
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter>
<filter-name>HttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>HttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Handles Spring requests -->
<servlet>
<servlet-name>securitytest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/spring/webmvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>requestFactory</servlet-name>
<servlet-class>com.securitytest.server.CustomRequestFactoryServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>securitytest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>requestFactory</servlet-name>
<url-pattern>/gwtRequest</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>10</session-timeout>
</session-config>
The CustomRequestFactoryServlet class extends RequestFactoryServlet providing an additional constructor to resolve Spring services and should not be relevant to security issues.
After entering username and password on the GWT widget a login service is invoked (via RequestFactory) that simply does the following:
public String loginUser(String username, String password) {
UsernamePasswordAuthenticationToken token =
new UsernamePasswordAuthenticationToken(username, password);
Authentication authenticatedUser = authenticationManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
return username;
}
So when I enter a URL like ../fooooooo I expect my application to redirect me to the login page (ApplicationScaffold.html). But only the URL in the browser´s address bar is set to ../ApplicationScaffold.html and nothing more happens.
What am I doing wrong?
The stack trace says the following:
[INFO] 2012-12-17 13:41:07,502 [btpool0-0] DEBUG org.springframework.security.web.FilterChainProxy - /fooooooooo at position 1 of 7 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
[INFO] 2012-12-17 13:41:07,502 [btpool0-0] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - No HttpSession currently exists
[INFO] 2012-12-17 13:41:07,502 [btpool0-0] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: null. A new one will be created.
[INFO] 2012-12-17 13:41:07,502 [btpool0-0] DEBUG org.springframework.security.web.FilterChainProxy - /fooooooooo at position 2 of 7 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
[INFO] 2012-12-17 13:41:07,502 [btpool0-0] DEBUG org.springframework.security.web.FilterChainProxy - /fooooooooo at position 3 of 7 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
[INFO] 2012-12-17 13:41:07,502 [btpool0-0] DEBUG org.springframework.security.web.FilterChainProxy - /fooooooooo at position 4 of 7 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
[INFO] 2012-12-17 13:41:07,503 [btpool0-0] DEBUG org.springframework.security.web.authentication.AnonymousAuthenticationFilter - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken#9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
[INFO] 2012-12-17 13:41:07,503 [btpool0-0] DEBUG org.springframework.security.web.FilterChainProxy - /fooooooooo at position 5 of 7 in additional filter chain; firing Filter: 'SessionManagementFilter'
[INFO] 2012-12-17 13:41:07,504 [btpool0-0] DEBUG org.springframework.security.web.session.SessionManagementFilter - Requested session ID1nkvhmubnkz6h is invalid.
[INFO] 2012-12-17 13:41:07,504 [btpool0-0] DEBUG org.springframework.security.web.FilterChainProxy - /fooooooooo at position 6 of 7 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
[INFO] 2012-12-17 13:41:07,504 [btpool0-0] DEBUG org.springframework.security.web.FilterChainProxy - /fooooooooo at position 7 of 7 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
[INFO] 2012-12-17 13:41:07,504 [btpool0-0] DEBUG org.springframework.security.web.util.AntPathRequestMatcher - Checking match of request : '/fooooooooo'; against '/applicationscaffold.html'
[INFO] 2012-12-17 13:41:07,504 [btpool0-0] DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Secure object: FilterInvocation: URL: /fooooooooo; Attributes: [hasRole('ROLE_USER')]
[INFO] 2012-12-17 13:41:07,504 [btpool0-0] DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken#9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
[INFO] 2012-12-17 13:41:07,504 [btpool0-0] DEBUG org.springframework.security.access.vote.AffirmativeBased - Voter: org.springframework.security.web.access.expression.WebExpressionVoter#5f8d13b8, returned: -1
[INFO] 2012-12-17 13:41:07,504 [btpool0-0] DEBUG org.springframework.security.web.access.ExceptionTranslationFilter - Access is denied (user is anonymous); redirecting to authentication entry point
[INFO] org.springframework.security.access.AccessDeniedException: Access is denied
...
[INFO] 2012-12-17 13:41:07,506 [btpool0-0] DEBUG org.springframework.security.web.savedrequest.HttpSessionRequestCache - DefaultSavedRequest added to Session: DefaultSavedRequest[http://127.0.0.1:8888/fooooooooo]
[INFO] 2012-12-17 13:41:07,506 [btpool0-0] DEBUG org.springframework.security.web.access.ExceptionTranslationFilter - Calling Authentication entry point.
[INFO] 2012-12-17 13:41:07,506 [btpool0-0] DEBUG org.springframework.security.web.DefaultRedirectStrategy - Redirecting to 'http://127.0.0.1:8888/ApplicationScaffold.html'
[INFO] 2012-12-17 13:41:07,506 [btpool0-0] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
[INFO] 2012-12-17 13:41:07,506 [btpool0-0] DEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
[INFO] 2012-12-17 13:41:07,543 [btpool0-0] DEBUG org.springframework.security.web.FilterChainProxy - /ApplicationScaffold.html at position 1 of 7 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
[INFO] 2012-12-17 13:41:07,543 [btpool0-0] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - HttpSession returned null object for SPRING_SECURITY_CONTEXT
[INFO] 2012-12-17 13:41:07,543 [btpool0-0] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: org.mortbay.jetty.servlet.HashSessionManager$Session:q0k5u6clocpc#1530548245. A new one will be created.
[INFO] 2012-12-17 13:41:07,543 [btpool0-0] DEBUG org.springframework.security.web.FilterChainProxy - /ApplicationScaffold.html at position 2 of 7 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
[INFO] 2012-12-17 13:41:07,543 [btpool0-0] DEBUG org.springframework.security.web.savedrequest.DefaultSavedRequest - pathInfo: both null (property equals)
[INFO] 2012-12-17 13:41:07,543 [btpool0-0] DEBUG org.springframework.security.web.savedrequest.DefaultSavedRequest - queryString: both null (property equals)
[INFO] 2012-12-17 13:41:07,543 [btpool0-0] DEBUG org.springframework.security.web.savedrequest.DefaultSavedRequest - requestURI: arg1=/fooooooooo; arg2=/ApplicationScaffold.html (property not equals)
[INFO] 2012-12-17 13:41:07,543 [btpool0-0] DEBUG org.springframework.security.web.savedrequest.HttpSessionRequestCache - saved request doesn't match
[INFO] 2012-12-17 13:41:07,543 [btpool0-0] DEBUG org.springframework.security.web.FilterChainProxy - /ApplicationScaffold.html at position 3 of 7 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
[INFO] 2012-12-17 13:41:07,544 [btpool0-0] DEBUG org.springframework.security.web.FilterChainProxy - /ApplicationScaffold.html at position 4 of 7 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
[INFO] 2012-12-17 13:41:07,544 [btpool0-0] DEBUG org.springframework.security.web.authentication.AnonymousAuthenticationFilter - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken#9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: q0k5u6clocpc; Granted Authorities: ROLE_ANONYMOUS'
[INFO] 2012-12-17 13:41:07,544 [btpool0-0] DEBUG org.springframework.security.web.FilterChainProxy - /ApplicationScaffold.html at position 5 of 7 in additional filter chain; firing Filter: 'SessionManagementFilter'
[INFO] 2012-12-17 13:41:07,544 [btpool0-0] DEBUG org.springframework.security.web.FilterChainProxy - /ApplicationScaffold.html at position 6 of 7 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
[INFO] 2012-12-17 13:41:07,544 [btpool0-0] DEBUG org.springframework.security.web.FilterChainProxy - /ApplicationScaffold.html at position 7 of 7 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
[INFO] 2012-12-17 13:41:07,544 [btpool0-0] DEBUG org.springframework.security.web.util.AntPathRequestMatcher - Checking match of request : '/applicationscaffold.html'; against '/applicationscaffold.html'
[INFO] 2012-12-17 13:41:07,544 [btpool0-0] DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Secure object: FilterInvocation: URL: /ApplicationScaffold.html; Attributes: [permitAll]
[INFO] 2012-12-17 13:41:07,544 [btpool0-0] DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken#9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: q0k5u6clocpc; Granted Authorities: ROLE_ANONYMOUS
[INFO] 2012-12-17 13:41:07,544 [btpool0-0] DEBUG org.springframework.security.access.vote.AffirmativeBased - Voter: org.springframework.security.web.access.expression.WebExpressionVoter#5f8d13b8, returned: 1
[INFO] 2012-12-17 13:41:07,544 [btpool0-0] DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Authorization successful
[INFO] 2012-12-17 13:41:07,544 [btpool0-0] DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - RunAsManager did not change Authentication object
[INFO] 2012-12-17 13:41:07,544 [btpool0-0] DEBUG org.springframework.security.web.FilterChainProxy - /ApplicationScaffold.html reached end of additional filter chain; proceeding with original chain
[INFO] 2012-12-17 13:41:07,544 [btpool0-0] DEBUG org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter - Opening JPA EntityManager in OpenEntityManagerInViewFilter
[INFO] 2012-12-17 13:41:07,544 [btpool0-0] DEBUG org.hibernate.impl.SessionImpl - opened session at timestamp: 13557480675
[INFO] 2012-12-17 13:41:07,545 [btpool0-0] DEBUG org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'securitytest' processing GET request for [/ApplicationScaffold.html]
[INFO] 2012-12-17 13:41:07,545 [btpool0-0] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Looking up handler method for path /ApplicationScaffold.html
[INFO] 2012-12-17 13:41:07,545 [btpool0-0] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Did not find handler method for [/ApplicationScaffold.html]
[INFO] 2012-12-17 13:41:07,545 [btpool0-0] DEBUG org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Matching patterns for request [/ApplicationScaffold.html] are [/**]
[INFO] 2012-12-17 13:41:07,545 [btpool0-0] DEBUG org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - URI Template variables for request [/ApplicationScaffold.html] are {}
[INFO] 2012-12-17 13:41:07,545 [btpool0-0] DEBUG org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapping [/ApplicationScaffold.html] to HandlerExecutionChain with handler [org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler#3e3bfa58] and 1 interceptor
[INFO] 2012-12-17 13:41:07,545 [btpool0-0] DEBUG org.springframework.web.servlet.DispatcherServlet - Last-Modified value for [/ApplicationScaffold.html] is: -1
[INFO] 2012-12-17 13:41:07,547 [btpool0-0] DEBUG org.springframework.web.servlet.DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'securitytest': assuming HandlerAdapter completed request handling
[INFO] 2012-12-17 13:41:07,547 [btpool0-0] DEBUG org.springframework.web.servlet.DispatcherServlet - Successfully completed request
[INFO] 2012-12-17 13:41:07,547 [btpool0-0] DEBUG org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter - Closing JPA EntityManager in OpenEntityManagerInViewFilter
[INFO] 2012-12-17 13:41:07,547 [btpool0-0] DEBUG org.springframework.orm.jpa.EntityManagerFactoryUtils - Closing JPA EntityManager
[INFO] 2012-12-17 13:41:07,547 [btpool0-0] DEBUG org.springframework.security.web.access.ExceptionTranslationFilter - Chain processed normally
[INFO] 2012-12-17 13:41:07,547 [btpool0-0] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
[INFO] 2012-12-17 13:41:07,547 [btpool0-0] DEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
[INFO] 2012-12-17 13:41:07,583 [btpool0-0] DEBUG org.springframework.security.web.FilterChainProxy - /applicationScaffold/C142D67E9948229BE2B28E2A99E7C59A.cache.html at position 1 of 7 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
[INFO] 2012-12-17 13:41:07,583 [btpool0-0] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - HttpSession returned null object for SPRING_SECURITY_CONTEXT
[INFO] 2012-12-17 13:41:07,583 [btpool0-0] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: org.mortbay.jetty.servlet.HashSessionManager$Session:q0k5u6clocpc#1530548245. A new one will be created.
[INFO] 2012-12-17 13:41:07,583 [btpool0-0] DEBUG org.springframework.security.web.FilterChainProxy - /applicationScaffold/C142D67E9948229BE2B28E2A99E7C59A.cache.html at position 2 of 7 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
[INFO] 2012-12-17 13:41:07,583 [btpool0-0] DEBUG org.springframework.security.web.savedrequest.DefaultSavedRequest - pathInfo: both null (property equals)
[INFO] 2012-12-17 13:41:07,583 [btpool0-0] DEBUG org.springframework.security.web.savedrequest.DefaultSavedRequest - queryString: both null (property equals)
[INFO] 2012-12-17 13:41:07,584 [btpool0-0] DEBUG org.springframework.security.web.savedrequest.DefaultSavedRequest - requestURI: arg1=/fooooooooo; arg2=/applicationScaffold/C142D67E9948229BE2B28E2A99E7C59A.cache.html (property not equals)
[INFO] 2012-12-17 13:41:07,584 [btpool0-0] DEBUG org.springframework.security.web.savedrequest.HttpSessionRequestCache - saved request doesn't match
[INFO] 2012-12-17 13:41:07,584 [btpool0-0] DEBUG org.springframework.security.web.FilterChainProxy - /applicationScaffold/C142D67E9948229BE2B28E2A99E7C59A.cache.html at position 3 of 7 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
[INFO] 2012-12-17 13:41:07,584 [btpool0-0] DEBUG org.springframework.security.web.FilterChainProxy - /applicationScaffold/C142D67E9948229BE2B28E2A99E7C59A.cache.html at position 4 of 7 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
[INFO] 2012-12-17 13:41:07,584 [btpool0-0] DEBUG org.springframework.security.web.authentication.AnonymousAuthenticationFilter - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken#9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: q0k5u6clocpc; Granted Authorities: ROLE_ANONYMOUS'
[INFO] 2012-12-17 13:41:07,584 [btpool0-0] DEBUG org.springframework.security.web.FilterChainProxy - /applicationScaffold/C142D67E9948229BE2B28E2A99E7C59A.cache.html at position 5 of 7 in additional filter chain; firing Filter: 'SessionManagementFilter'
[INFO] 2012-12-17 13:41:07,584 [btpool0-0] DEBUG org.springframework.security.web.FilterChainProxy - /applicationScaffold/C142D67E9948229BE2B28E2A99E7C59A.cache.html at position 6 of 7 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
[INFO] 2012-12-17 13:41:07,584 [btpool0-0] DEBUG org.springframework.security.web.FilterChainProxy - /applicationScaffold/C142D67E9948229BE2B28E2A99E7C59A.cache.html at position 7 of 7 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
[INFO] 2012-12-17 13:41:07,584 [btpool0-0] DEBUG org.springframework.security.web.util.AntPathRequestMatcher - Checking match of request : '/applicationscaffold/c142d67e9948229be2b28e2a99e7c59a.cache.html'; against '/applicationscaffold.html'
[INFO] 2012-12-17 13:41:07,584 [btpool0-0] DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Secure object: FilterInvocation: URL: /applicationScaffold/C142D67E9948229BE2B28E2A99E7C59A.cache.html; Attributes: [hasRole('ROLE_USER')]
[INFO] 2012-12-17 13:41:07,584 [btpool0-0] DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken#9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: q0k5u6clocpc; Granted Authorities: ROLE_ANONYMOUS
[INFO] 2012-12-17 13:41:07,584 [btpool0-0] DEBUG org.springframework.security.access.vote.AffirmativeBased - Voter: org.springframework.security.web.access.expression.WebExpressionVoter#5f8d13b8, returned: -1
[INFO] 2012-12-17 13:41:07,584 [btpool0-0] DEBUG org.springframework.security.web.access.ExceptionTranslationFilter - Access is denied (user is anonymous); redirecting to authentication entry point
[INFO] org.springframework.security.access.AccessDeniedException: Access is denied
Pure GWT solution:
Do not use http element at all (http tag from config namespace)
Define your AuthenticationRpcService
Add AuthenticationRpcService.authenticate(user,password) method
Inject into AuthenticationServiceImpl AuthenticationProvider bean from security-context.xml
Implement AuthenticationRpcService.authenticate(user,password) as :
User user = new User(login, password, true, true, true, true, new ArrayList<GrantedAuthority>());
Authentication auth = new UsernamePasswordAuthenticationToken(user, password,
new ArrayList<GrantedAuthority>());
try {
auth = this.authenticationProvider.authenticate(auth);
} catch (BadCredentialsException e) {
throw new ClientSideBadCredentialsException(e.getMessage(), e);
}
SecurityContext sc = new SecurityContextImpl();
sc.setAuthentication(auth);
SecurityContextHolder.setContext(sc);
Ensure that spring security filter chain is executed during processing of each your GWT RPC call (to be sure that SecurityContext populated into SecurityContextHolder).
Secure all business services with #RolesAllowed({ "ADMIN_ROLE", "USER_ROLE" }) annotations
Prepare your own ClientSideAcessDeniedException that can be used on client side
In a case of spring AcessDeniedException propogate ClientSideAcessDeniedException to client side
On client side set up UncaughtExceptionHandler via GWT.setUncaughtExceptionHandler
In UncaughtExceptionHandler detect CustomAcessDeniedException and then show error to user.
I've found that all you can protect in gwt using Spring Security are the RPC calls but as far as the gui you can't. Remember they are javascript so there is no url to define in the security configuration. That is why all examples have the jsp login page. You would then have to implement some type of client side security using the userContext for frontend .
You need to figure out why your user is considered anonymous (line 77 in stacktrace). I suppose Spring then sends another redirect (to the login) but the GWT callback doesn't know what to do with HTTP 302?

Resources