Issue during Spring Security integration with Siteminder SSO integration - spring

Spring's DispatcherServlet servlet sometimes calls GET request instead of POST request. It has to call POST method all the time as per JSP form method="post".
(DispatcherServlet.java:823) - DispatcherServlet with name 'springmvc' processing GET request for [/change.do]
All the configurations are correct. I checked and searched online. There is no correct answer for this.
I am using:
<spring.version>3.2.3.RELEASE</spring.version>
<spring.security.version>3.1.4.RELEASE</spring.security.version>
I am using lots of Spring filters and Tomcat 6.0.
<security:custom-filter position="PRE_AUTH_FILTER" ref="siteminderFilter" />
Why Spring's DispatcherServlet servlet calls GET method instead of POST method occasionally? 90% of time it calls POST which is correct but 10% time it calls GET method for any of the forms which has method="post".
Tomcat debug log:
2017-01-27 11:30:08,811 [TP-Processor19] DEBUG (AntPathRequestMatcher.java:116) - Checking match of request : '/change.do'; against '/*.do'
2017-01-27 11:30:08,812 [TP-Processor19] DEBUG (AbstractSecurityInterceptor.java:194) - Secure object: FilterInvocation: URL: /change.do; Attributes: [IS_AUTHENTICATED_REMEMBERED]
2017-01-27 11:30:08,814 [TP-Processor19] DEBUG (AbstractSecurityInterceptor.java:310) - Previously Authenticated: org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken#a24fd89f: Principal: ...#fdf65be0: Username: ABS; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: Admin; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#59b2: RemoteIpAddress: 10.4.89.65; SessionId: null; Granted Authorities: Admin
2017-01-27 11:30:08,815 [TP-Processor19] DEBUG (AffirmativeBased.java:65) - Voter: org.springframework.security.access.vote.RoleVoter#4c019ea6, returned: 0
2017-01-27 11:30:08,817 [TP-Processor19] DEBUG (AffirmativeBased.java:65) - Voter: org.springframework.security.access.vote.AuthenticatedVoter#7e56cb45, returned: 1
2017-01-27 11:30:08,818 [TP-Processor19] DEBUG (AbstractSecurityInterceptor.java:215) - Authorization successful
2017-01-27 11:30:08,820 [TP-Processor19] DEBUG (AbstractSecurityInterceptor.java:227) - RunAsManager did not change Authentication object
2017-01-27 11:30:08,821 [TP-Processor19] DEBUG (FilterChainProxy.java:323) - /change.do reached end of additional filter chain; proceeding with original chain
2017-01-27 11:30:08,823 [TP-Processor19] DEBUG (DispatcherServlet.java:823) - DispatcherServlet with name 'springmvc' **processing GET request** for [/change.do]

Related

Spring http API returns error 500 but error is not logged in console

I have a spring boot application, (spring 5.0.7.Release , spring boot version 2.0.3).
Where I try to login from my angular 4 app, I get an error 500
{"timestamp":"2018-07-13","status":500,"error":"Internal Server Error","message":"org.springframework.session.MapSession.getCreationTime()Ljava/time/Instant;","path":"/security/signIn/password"}
But in eclipse my console show only this
2018-07-13 12:11:59.243 DEBUG 64187 --- [nio-9000-exec-2]
f.p.a.c.CustomBasicAuthenticationFilter : Authentication success:
org.springframework.security.authentication.UsernamePasswordAuthenticationToken#aa6b860d:
Principal:
fr.pangeeconseil.purchase.core.domain.security.AuthenticatedUserDTO#75136264;
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: SUPER_ADMINISTRATOR 2018-07-13 12:11:59.306 DEBUG 64187
--- [nio-9000-exec-2] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing POST
request for [/error] 2018-07-13 12:11:59.311 DEBUG 64187 ---
[nio-9000-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking
up handler method for path /error 2018-07-13 12:11:59.313 DEBUG 64187
--- [nio-9000-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public
org.springframework.http.ResponseEntity>
org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)]
2018-07-13 12:11:59.314 DEBUG 64187 --- [nio-9000-exec-2]
f.p.a.c.web.CustomWebContentInterceptor : Looking up cache seconds
for [/error] 2018-07-13 12:11:59.314 DEBUG 64187 --- [nio-9000-exec-2]
f.p.a.c.web.CustomWebContentInterceptor : Applying default cache
seconds to [/error] 2018-07-13 12:11:59.402 DEBUG 64187 ---
[nio-9000-exec-2] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Written
[{timestamp=Fri Jul 13 12:11:59 CEST 2018, status=500, error=Internal
Server Error,
message=org.springframework.session.MapSession.getCreationTime()Ljava/time/Instant;,
path=/security/signIn/password}] as "application/json" using
[org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#305deb42]
2018-07-13 12:11:59.403 DEBUG 64187 --- [nio-9000-exec-2]
o.s.web.servlet.DispatcherServlet : Null ModelAndView returned
to DispatcherServlet with name 'dispatcherServlet': assuming
HandlerAdapter completed request handling 2018-07-13 12:11:59.404
DEBUG 64187 --- [nio-9000-exec-2] o.s.web.servlet.DispatcherServlet
: Successfully completed request
Important informations :
we use redis session with the following reference in our gradle.build
compile 'org.springframework.data:spring-data-redis:2.0.8.RELEASE'
compile "org.springframework.session:spring-session:1.3.3.RELEASE"
compile "org.springframework.session:spring-session-core:2.0.0.RELEASE"
compile "org.springframework.session:spring-session-data-redis:2.0.4.RELEASE"
Here is our SecurityConfig : https://gist.github.com/RemiBou/fe3a28644cddf8b4e72ad9fdeb26d24e
I'm a very beginner with spring/spring boot so it might be obvious but I couldn't find anything online.
I figured it out : spring-session is obsolete, I needed to remove it, and change a few things in securityConfiguration because some classes where removed / renamed.

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.

Never go in WebSecurityConfigurerAdapter

I made a simple rest service and I wanted to add a simple security on the api.
So I created an WebSecurityConfigurerAdapter :
package org.test.subscription.webservice.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("test1").password("test1").roles("superAdminRole").and()
.withUser("test2").password("test2").roles("superAdminRole");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic()
.and()
.authorizeRequests()
.anyRequest().hasRole("webserviceReadRole").and()
.csrf().disable();
}
}
And this is my main runner:
package org.test.subscription.webservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
But when I call something inside my API,I'm not authenticate at all, and I get my "hello world" response. So he never check my role. Any ideas why?
Your example should work as you expect it (tested in boot 1.5.7 and also 2.0.0 M3). So I would recommend that you try the following. First verify some trivial things:
That you do not have anything that disables security checks in your application.properties or the corresponding yaml (e.g. something like security.ignored and Co.).
That you do not have another WebSecurityConfigurerAdapter in your application.
That your classes are scanned correctly by Spring.
That you do not have some strange cookies in the browser. E.g. try the same request by starting the browser in private mode or use curl or something similar.
If it still does not work enable the Spring Security debugger for a deeper insight on what is going on under the hood and why you see unexpected behavior. This may be achieved in the following way:
#EnableWebSecurity(debug = true)
This will hint Spring to print lots of extra details which will help you find out what is wrong. In your setup you should see something like the following in the logs when you issue an request.
First, the request itself with the proper headers. Example with the most important parts:
Request received for GET '/path/to/your/api':
org.apache.catalina.connector.RequestFacade#58a4ad1c
authorization: Basic dGVzdDE6dGVzdDE=
cookie: JSESSIONID=9E4EBB889BB178E05446104EF2787C2F
Then you will see the filter chain managed by the FilterChainProxy and matched with your request (note that there might be other filter chains depending on the setup of your app - the log shows the matched chain which may not be the one that you expect):
Security filter chain: [
WebAsyncManagerIntegrationFilter
SecurityContextPersistenceFilter
HeaderWriterFilter
CsrfFilter
LogoutFilter
BasicAuthenticationFilter
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
AnonymousAuthenticationFilter
SessionManagementFilter
ExceptionTranslationFilter
FilterSecurityInterceptor
]
Then lots of DEBUG messages will follow in the log. Please pay special attention to the messages created around the BasicAuthenticationFilter:
2017-10-07 14:42:21.644 DEBUG 56071 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /pat/to/your/api at position 6 of 12 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
2017-10-07 14:42:21.645 DEBUG 56071 --- [nio-8080-exec-2] o.s.s.w.a.www.BasicAuthenticationFilter : Basic Authentication Authorization header found for user 'test1'
2017-10-07 14:42:21.645 DEBUG 56071 --- [nio-8080-exec-2] o.s.s.authentication.ProviderManager : Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
2017-10-07 14:42:21.647 DEBUG 56071 --- [nio-8080-exec-2] o.s.s.w.a.www.BasicAuthenticationFilter : Authentication success: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#8fc16c08: Principal: org.springframework.security.core.userdetails.User#6924ddf: Username: test1; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_superAdminRole; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#0: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 9E4EBB889BB178E05446104EF2787C2F; Granted Authorities: ROLE_superAdminRole
2
And also to the FilterSecurityInterceptor which should output the successful authorization message:
2017-10-07 14:42:21.649 DEBUG 56071 --- [nio-8080-exec-2] o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#8fc16c08: Principal: org.springframework.security.core.userdetails.User#6924ddf: Username: test1; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_superAdminRole; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#0: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 9E4EBB889BB178E05446104EF2787C2F; Granted Authorities: ROLE_superAdminRole
2017-10-07 14:42:21.649 DEBUG 56071 --- [nio-8080-exec-2] o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.web.access.expression.WebExpressionVoter#1ca8b2d, returned: 1
2017-10-07 14:42:21.649 DEBUG 56071 --- [nio-8080-exec-2] o.s.s.w.a.i.FilterSecurityInterceptor : Authorization successful
Armed with all these details approach SO further :-)

Spring-boot oauth2 /oauth/token 404

so I have an existing SpringBoot project.
a) I added this at the top of my main #Configuration class
#Import({ WebSecurityConfiguration.class, OAuth2ServerConfiguration.class })
b) The contents of the above 2 classes are the same as what is in this project: https://github.com/royclarkson/spring-rest-service-oauth/tree/master/src/main/java/hello
c) I startup my app and see this as expected in the logs:
2015-10-28 20:05:40,037 INFO [FrameworkEndpointHandlerMapping] Mapped "{[/oauth/authorize]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.authorize(java.util.Map<java.lang.String, java.lang.Object>,java.util.Map<java.lang.String, java.lang.String>,org.springframework.web.bind.support.SessionStatus,java.security.Principal)
2015-10-28 20:05:40,037 INFO [FrameworkEndpointHandlerMapping] Mapped "{[/oauth/authorize],methods=[POST],params=[user_oauth_approval]}" onto public org.springframework.web.servlet.View org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.approveOrDeny(java.util.Map<java.lang.String, java.lang.String>,java.util.Map<java.lang.String, ?>,org.springframework.web.bind.support.SessionStatus,java.security.Principal)
2015-10-28 20:05:40,040 INFO [FrameworkEndpointHandlerMapping] Mapped "{[/oauth/token],methods=[GET]}" onto public org.springframework.http.ResponseEntity<org.springframework.security.oauth2.common.OAuth2AccessToken> org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.getAccessToken(java.security.Principal,java.util.Map<java.lang.String, java.lang.String>) throws org.springframework.web.HttpRequestMethodNotSupportedException
2015-10-28 20:05:40,040 INFO [FrameworkEndpointHandlerMapping] Mapped "{[/oauth/token],methods=[POST]}" onto public org.springframework.http.ResponseEntity<org.springframework.security.oauth2.common.OAuth2AccessToken> org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(java.security.Principal,java.util.Map<java.lang.String, java.lang.String>) throws org.springframework.web.HttpRequestMethodNotSupportedException
2015-10-28 20:05:40,041 INFO [FrameworkEndpointHandlerMapping] Mapped "{[/oauth/check_token]}" onto public java.util.Map<java.lang.String, ?> org.springframework.security.oauth2.provider.endpoint.CheckTokenEndpoint.checkToken(java.lang.String)
2015-10-28 20:05:40,041 INFO [FrameworkEndpointHandlerMapping] Mapped "{[/oauth/confirm_access]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.security.oauth2.provider.endpoint.WhitelabelApprovalEndpoint.getAccessConfirmation(java.util.Map<java.lang.String, java.lang.Object>,javax.servlet.http.HttpServletRequest) throws java.lang.Exception
2015-10-28 20:05:40,042 INFO [FrameworkEndpointHandlerMapping] Mapped "{[/oauth/error]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.security.oauth2.provider.endpoint.WhitelabelErrorEndpoint.handleError(javax.servlet.http.HttpServletRequest)
d) When I go to /greeting I get the following as expected:
{ "error": "unauthorized", "error_description": "Full authentication is required to access this resource" }
e) When I attempt to POST to /oauth/token I see the below in the logs... but I get a 404 and no token back. This has been driving me nuts now for 2 days trying to figure this out. Any help appreciated.
2015-10-28 20:08:59,713 DEBUG [FilterSecurityInterceptor] Secure object: FilterInvocation: URL: /oauth/token; Attributes: [fullyAuthenticated]
2015-10-28 20:08:59,713 DEBUG [FilterSecurityInterceptor] Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#7159411d: Principal: org.springframework.security.core.userdetails.User#8e81ee76: Username: clientapp; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: USER; 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: USER
2015-10-28 20:08:59,713 DEBUG [AffirmativeBased] Voter: org.springframework.security.web.access.expression.WebExpressionVoter#44aef1f8, returned: 1
2015-10-28 20:08:59,713 DEBUG [FilterSecurityInterceptor] Authorization successful
2015-10-28 20:08:59,713 DEBUG [FilterSecurityInterceptor] RunAsManager did not change Authentication object
2015-10-28 20:08:59,713 DEBUG [FilterChainProxy] /oauth/token reached end of additional filter chain; proceeding with original chain
2015-10-28 20:08:59,714 DEBUG [ExceptionTranslationFilter] Chain processed normally
2015-10-28 20:08:59,714 DEBUG [SecurityContextPersistenceFilter] SecurityContextHolder now cleared, as request processing completed
Again, I just get a 404
The problem is you are not adding Authorization in the header.Without adding header you cannot access the resources, and sometimes it shows error of Bad Credentials.For postman POST call for /oauth/token at there authorization is needed in header.
If i am not adding any authorization to the header.It shows me following error:-
{
"error": "unauthorized",
"error_description": "Full authentication is required to access this resource"
}
You can create Authorization with the help of Base64Encoder
The problem was that in my main #Configuration annotated class I had a dispatcherServlet #Bean registered, which was intercepting all the requests. Once I changed the method name to something other than dispatcherServlet() it fixed the issue:
BAD:
#Bean
public ServletRegistrationBean dispatcherServlet() {
CXFServlet cxfServlet = new CXFServlet();
return new ServletRegistrationBean(cxfServlet, "/x/*");
}
GOOD:
#Bean
public ServletRegistrationBean thisFixedMyIssue() {
CXFServlet cxfServlet = new CXFServlet();
return new ServletRegistrationBean(cxfServlet, "/x/*");
}

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"

Resources