Access denied in client credentials flow - spring-security

What I do:
I am preparing spring boot oauth2 authorization server with two flows:
access code (users)
client credentials (services)
Problem
When I am using curl to get access token with client credentials flow:
curl --request POST \
-vv \
--url 'http://localhost:9000/oauth/token' \
--header "Authorization: Basic Y2xhc3Nlcy1jYWxlbmRhci1jbGllbnQ6cGFzc3dvcmQ=" \
--header 'content-type: application/x-www-form-urlencoded' \
--data grant_type=client_credentials
I am redirected to login page.
In logs I see access denied.
Config
#Configuration(proxyBeanMethods = false)
#EnableWebSecurity
public class AuthorizationServerConfig {
#Bean
#Order(Ordered.HIGHEST_PRECEDENCE)
public SecurityFilterChain authServerSecurityFilterChain(HttpSecurity http) throws Exception {
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
return http.formLogin(Customizer.withDefaults()).build();
}
#Bean
SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests(authorizeRequests ->
authorizeRequests.anyRequest().authenticated()
)
.formLogin(withDefaults());
return http.build();
}
#Bean
public RegisteredClientRepository registeredClientRepository() {
RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("classes-calendar-client")
.clientSecret("{noop}password") // FIXME this accepts no password encoding
.clientName("classes-calendar-client")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
.redirectUri("http://auth-service:8080/login/oauth2/code/classes-calendar-client")
.redirectUri("http://auth-service:8080/authorized")
.scope(OidcScopes.OPENID)
.scope("all")
.build();
return new InMemoryRegisteredClientRepository(registeredClient);
}
#Bean
public JWKSource<SecurityContext> jwkSource() {
RSAKey rsaKey = generateRsa();
JWKSet jwkSet = new JWKSet(rsaKey);
return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
}
private static RSAKey generateRsa() {
KeyPair keyPair = generateRsaKey();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
return new RSAKey.Builder(publicKey)
.privateKey(privateKey)
.keyID(UUID.randomUUID().toString())
.build();
}
private static KeyPair generateRsaKey() {
KeyPair keyPair;
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
keyPair = keyPairGenerator.generateKeyPair();
} catch (Exception ex) {
throw new IllegalStateException(ex);
}
return keyPair;
}
#Bean
public ProviderSettings providerSettings() {
return ProviderSettings.builder()
.issuer("http://oauth2-service:9000")
.build();
}
#Bean
InMemoryUserDetailsManager userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("admin")
.password("password")
.roles("ADMIN", "USER")
.build();
UserDetails service = User.withDefaultPasswordEncoder()
.username("service")
.password("password")
.roles("SERVICE")
.build();
return new InMemoryUserDetailsManager(user, service);
}
}
Logs
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Trying to match request against DefaultSecurityFilterChain [RequestMatcher=org.springframework.security.config.annotation.web.configurers.oauth2.server.authorization.OAuth2AuthorizationServerConfigurer$$Lambda$617/0x0000000800fadcb8#2c2a027c, Filters=[org.springframework.security.web.session.DisableEncodeUrlFilter#118dcbbd, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#7d979d34, org.springframework.security.web.context.SecurityContextPersistenceFilter#36aa52d2, org.springframework.security.oauth2.server.authorization.web.ProviderContextFilter#1a47a1e8, org.springframework.security.web.header.HeaderWriterFilter#6cbe7d4d, org.springframework.security.web.csrf.CsrfFilter#141d3d43, org.springframework.security.web.authentication.logout.LogoutFilter#73ae0257, org.springframework.security.oauth2.server.authorization.web.OAuth2AuthorizationEndpointFilter#3d90eeb3, org.springframework.security.oauth2.server.authorization.oidc.web.OidcProviderConfigurationEndpointFilter#7650ded6, org.springframework.security.oauth2.server.authorization.web.NimbusJwkSetEndpointFilter#1084f78c, org.springframework.security.oauth2.server.authorization.web.OAuth2AuthorizationServerMetadataEndpointFilter#3df1a1ac, org.springframework.security.oauth2.server.authorization.web.OAuth2ClientAuthenticationFilter#2b38b1f, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#58606c91, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter#403c3a01, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter#350ec690, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#16a35bd, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#ba17be6, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#49cb1baf, org.springframework.security.web.session.SessionManagementFilter#3679d92e, org.springframework.security.web.access.ExceptionTranslationFilter#3456558, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#261db982, org.springframework.security.oauth2.server.authorization.web.OAuth2TokenEndpointFilter#18a25bbd, org.springframework.security.oauth2.server.authorization.web.OAuth2TokenIntrospectionEndpointFilter#77f905e3, org.springframework.security.oauth2.server.authorization.web.OAuth2TokenRevocationEndpointFilter#1192b58e, org.springframework.security.oauth2.server.authorization.oidc.web.OidcUserInfoEndpointFilter#f5ce0bb]] (1/2)
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Trying to match request against DefaultSecurityFilterChain [RequestMatcher=any request, Filters=[org.springframework.security.web.session.DisableEncodeUrlFilter#3e4e8fdf, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#6a1d6ef2, org.springframework.security.web.context.SecurityContextPersistenceFilter#7f973a14, org.springframework.security.web.header.HeaderWriterFilter#2c991465, org.springframework.security.web.csrf.CsrfFilter#2740e316, org.springframework.security.web.authentication.logout.LogoutFilter#1cfc2538, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#42cc183e, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter#3451f01d, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter#2721044, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#76130a29, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#124d02b2, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#205df5dc, org.springframework.security.web.session.SessionManagementFilter#5fef2aac, org.springframework.security.web.access.ExceptionTranslationFilter#5b5a4aed, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#53e76c11]] (2/2)
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Securing POST /oauth/token
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Invoking DisableEncodeUrlFilter (1/15)
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Invoking WebAsyncManagerIntegrationFilter (2/15)
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Invoking SecurityContextPersistenceFilter (3/15)
--- [nio-9000-exec-1] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
--- [nio-9000-exec-1] w.c.HttpSessionSecurityContextRepository : Created SecurityContextImpl [Null authentication]
--- [nio-9000-exec-1] s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder to empty SecurityContext
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Invoking HeaderWriterFilter (4/15)
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Invoking CsrfFilter (5/15)
--- [nio-9000-exec-1] o.s.security.web.csrf.CsrfFilter : Invalid CSRF token found for http://localhost:9000/oauth/token
--- [nio-9000-exec-1] o.s.s.w.access.AccessDeniedHandlerImpl : Responding with 403 status code
--- [nio-9000-exec-1] o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match request to [Is Secure]
--- [nio-9000-exec-1] w.c.HttpSessionSecurityContextRepository : Did not store empty SecurityContext
--- [nio-9000-exec-1] w.c.HttpSessionSecurityContextRepository : Did not store empty SecurityContext
--- [nio-9000-exec-1] s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Trying to match request against DefaultSecurityFilterChain [RequestMatcher=org.springframework.security.config.annotation.web.configurers.oauth2.server.authorization.OAuth2AuthorizationServerConfigurer$$Lambda$617/0x0000000800fadcb8#2c2a027c, Filters=[org.springframework.security.web.session.DisableEncodeUrlFilter#118dcbbd, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#7d979d34, org.springframework.security.web.context.SecurityContextPersistenceFilter#36aa52d2, org.springframework.security.oauth2.server.authorization.web.ProviderContextFilter#1a47a1e8, org.springframework.security.web.header.HeaderWriterFilter#6cbe7d4d, org.springframework.security.web.csrf.CsrfFilter#141d3d43, org.springframework.security.web.authentication.logout.LogoutFilter#73ae0257, org.springframework.security.oauth2.server.authorization.web.OAuth2AuthorizationEndpointFilter#3d90eeb3, org.springframework.security.oauth2.server.authorization.oidc.web.OidcProviderConfigurationEndpointFilter#7650ded6, org.springframework.security.oauth2.server.authorization.web.NimbusJwkSetEndpointFilter#1084f78c, org.springframework.security.oauth2.server.authorization.web.OAuth2AuthorizationServerMetadataEndpointFilter#3df1a1ac, org.springframework.security.oauth2.server.authorization.web.OAuth2ClientAuthenticationFilter#2b38b1f, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#58606c91, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter#403c3a01, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter#350ec690, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#16a35bd, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#ba17be6, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#49cb1baf, org.springframework.security.web.session.SessionManagementFilter#3679d92e, org.springframework.security.web.access.ExceptionTranslationFilter#3456558, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#261db982, org.springframework.security.oauth2.server.authorization.web.OAuth2TokenEndpointFilter#18a25bbd, org.springframework.security.oauth2.server.authorization.web.OAuth2TokenIntrospectionEndpointFilter#77f905e3, org.springframework.security.oauth2.server.authorization.web.OAuth2TokenRevocationEndpointFilter#1192b58e, org.springframework.security.oauth2.server.authorization.oidc.web.OidcUserInfoEndpointFilter#f5ce0bb]] (1/2)
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Trying to match request against DefaultSecurityFilterChain [RequestMatcher=any request, Filters=[org.springframework.security.web.session.DisableEncodeUrlFilter#3e4e8fdf, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#6a1d6ef2, org.springframework.security.web.context.SecurityContextPersistenceFilter#7f973a14, org.springframework.security.web.header.HeaderWriterFilter#2c991465, org.springframework.security.web.csrf.CsrfFilter#2740e316, org.springframework.security.web.authentication.logout.LogoutFilter#1cfc2538, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#42cc183e, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter#3451f01d, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter#2721044, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#76130a29, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#124d02b2, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#205df5dc, org.springframework.security.web.session.SessionManagementFilter#5fef2aac, org.springframework.security.web.access.ExceptionTranslationFilter#5b5a4aed, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#53e76c11]] (2/2)
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Securing POST /error
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Invoking DisableEncodeUrlFilter (1/15)
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Invoking WebAsyncManagerIntegrationFilter (2/15)
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Invoking SecurityContextPersistenceFilter (3/15)
--- [nio-9000-exec-1] w.c.HttpSessionSecurityContextRepository : Did not find SecurityContext in HttpSession 50C9343D22CA6AC093145811E89DF30A using the SPRING_SECURITY_CONTEXT session attribute
--- [nio-9000-exec-1] w.c.HttpSessionSecurityContextRepository : Created SecurityContextImpl [Null authentication]
--- [nio-9000-exec-1] s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder to empty SecurityContext
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Invoking HeaderWriterFilter (4/15)
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Invoking CsrfFilter (5/15)
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Invoking LogoutFilter (6/15)
--- [nio-9000-exec-1] o.s.s.w.a.logout.LogoutFilter : Did not match request to Ant [pattern='/logout', POST]
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Invoking UsernamePasswordAuthenticationFilter (7/15)
--- [nio-9000-exec-1] w.a.UsernamePasswordAuthenticationFilter : Did not match request to Ant [pattern='/login', POST]
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Invoking DefaultLoginPageGeneratingFilter (8/15)
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Invoking DefaultLogoutPageGeneratingFilter (9/15)
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Invoking RequestCacheAwareFilter (10/15)
--- [nio-9000-exec-1] o.s.s.w.s.HttpSessionRequestCache : No saved request
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Invoking SecurityContextHolderAwareRequestFilter (11/15)
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Invoking AnonymousAuthenticationFilter (12/15)
--- [nio-9000-exec-1] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=127.0.0.1, SessionId=50C9343D22CA6AC093145811E89DF30A], Granted Authorities=[ROLE_ANONYMOUS]]
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Invoking SessionManagementFilter (13/15)
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Invoking ExceptionTranslationFilter (14/15)
--- [nio-9000-exec-1] o.s.security.web.FilterChainProxy : Invoking FilterSecurityInterceptor (15/15)
--- [nio-9000-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Did not re-authenticate AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=127.0.0.1, SessionId=50C9343D22CA6AC093145811E89DF30A], Granted Authorities=[ROLE_ANONYMOUS]] before authorizing
--- [nio-9000-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Authorizing filter invocation [POST /error] with attributes [authenticated]
--- [nio-9000-exec-1] o.s.s.w.a.expression.WebExpressionVoter : Voted to deny authorization
--- [nio-9000-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Failed to authorize filter invocation [POST /error] with attributes [authenticated] using AffirmativeBased [DecisionVoters=[org.springframework.security.web.access.expression.WebExpressionVoter#5d342959], AllowIfAllAbstainDecisions=false]
--- [nio-9000-exec-1] o.s.s.w.a.ExceptionTranslationFilter : Sending AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=127.0.0.1, SessionId=50C9343D22CA6AC093145811E89DF30A], Granted Authorities=[ROLE_ANONYMOUS]] to authentication entry point since access is denied
org.springframework.security.access.AccessDeniedException: Access is denied
at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:73) ~[spring-security-core-5.7.2.jar:5.7.2]
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.attemptAuthorization(AbstractSecurityInterceptor.java:239) ~[spring-security-core-5.7.2.jar:5.7.2]
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:208) ~[spring-security-core-5.7.2.jar:5.7.2]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:113) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:122) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:116) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:109) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:102) ~[spring-web-5.3.21.jar:5.3.21]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:237) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:223) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:223) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:217) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:102) ~[spring-web-5.3.21.jar:5.3.21]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:102) ~[spring-web-5.3.21.jar:5.3.21]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:112) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:82) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:102) ~[spring-web-5.3.21.jar:5.3.21]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:102) ~[spring-web-5.3.21.jar:5.3.21]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183) ~[spring-security-web-5.7.2.jar:5.7.2]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:354) ~[spring-web-5.3.21.jar:5.3.21]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:267) ~[spring-web-5.3.21.jar:5.3.21]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.21.jar:5.3.21]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.21.jar:5.3.21]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:102) ~[spring-web-5.3.21.jar:5.3.21]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:102) ~[spring-web-5.3.21.jar:5.3.21]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:711) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:461) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:385) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:313) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:403) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:249) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
...]
--- [nio-9000-exec-1] o.s.s.w.s.HttpSessionRequestCache : Did not save request since it did not match [And [Ant [pattern='/**', GET], Not [Ant [pattern='/**/favicon.*']], Not [MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.HeaderContentNegotiationStrategy#1e512e7c, matchingMediaTypes=[application/json], useEquals=false, ignoredMediaTypes=[*/*]]], Not [RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest]], Not [MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.HeaderContentNegotiationStrategy#29debe11, matchingMediaTypes=[multipart/form-data], useEquals=false, ignoredMediaTypes=[*/*]]], Not [MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.HeaderContentNegotiationStrategy#4cc94ca2, matchingMediaTypes=[text/event-stream], useEquals=false, ignoredMediaTypes=[*/*]]]]]
--- [nio-9000-exec-1] o.s.s.web.DefaultRedirectStrategy : Redirecting to http://localhost:9000/login
--- [nio-9000-exec-1] w.c.HttpSessionSecurityContextRepository : Did not store empty SecurityContext
--- [nio-9000-exec-1] w.c.HttpSessionSecurityContextRepository : Did not store empty SecurityContext
Question
What I need to do to make it work?

Take a look at the response to localhost:9000/.well-known/openid-configuration. You should see the token_endpoint URL is http://localhost:9000/oauth2/token.
Note: Since you've specified .issuer("http://oauth2-service:9000") in your ProviderSettings, it may reflect http://oauth2-service:9000/oauth2/token instead. If you omit this setting, it will detect the base url from the request automatically.
Make sure your request uses /oauth2/token instead. Also, make sure you include client_id=classes-calendar-client in your request, as I believe that is a required parameter for a client_credentials token request.

Related

Problem with Spring Authorization Server + Feign

everyone!
I have two modules,
authorization server
user service (also a resource server)
In my authoriztion server, i am trying to implement Feign Clients to get my user info from the user service.
i am using Authorization Server sample here, and add open feign.
Like this,
#Component
public class CustomUserDetailService implements UserDetailsService {
//feign
private final RemoteUserService remoteUserService;
public CustomUserDetailService(RemoteUserService remoteUserService){
this.remoteUserService = remoteUserService;
}
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return remoteUserService.getUser("test");
}
}
But i get a result like this
org.springframework.security.authentication.InternalAuthenticationServiceException: [401] during [POST] to [http://auth/auth/user/list] [RemoteUserService#getUserList(AuthUserDto)]: []
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:108) ~[spring-security-core-5.4.5.jar:5.4.5]
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:133) ~[spring-security-core-5.4.5.jar:5.4.5]
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:182) ~[spring-security-core-5.4.5.jar:5.4.5]
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:201) ~[spring-security-core-5.4.5.jar:5.4.5]
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:85) ~[spring-security-web-5.4.5.jar:5.4.5]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:222) [spring-security-web-5.4.5.jar:5.4.5]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212) [spring-security-web-5.4.5.jar:5.4.5]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) [spring-security-web-5.4.5.jar:5.4.5]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103) [spring-security-web-5.4.5.jar:5.4.5]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89) [spring-security-web-5.4.5.jar:5.4.5]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) [spring-security-web-5.4.5.jar:5.4.5]
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:132) [spring-security-web-5.4.5.jar:5.4.5]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.3.4.jar:5.3.4]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) [spring-security-web-5.4.5.jar:5.4.5]
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90) [spring-security-web-5.4.5.jar:5.4.5]
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75) [spring-security-web-5.4.5.jar:5.4.5]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.3.4.jar:5.3.4]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) [spring-security-web-5.4.5.jar:5.4.5]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:110) [spring-security-web-5.4.5.jar:5.4.5]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80) [spring-security-web-5.4.5.jar:5.4.5]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) [spring-security-web-5.4.5.jar:5.4.5]
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55) [spring-security-web-5.4.5.jar:5.4.5]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.3.4.jar:5.3.4]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) [spring-security-web-5.4.5.jar:5.4.5]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211) [spring-security-web-5.4.5.jar:5.4.5]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183) [spring-security-web-5.4.5.jar:5.4.5]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358) [spring-web-5.3.4.jar:5.3.4]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271) [spring-web-5.3.4.jar:5.3.4]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) [tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) [tomcat-embed-core-9.0.43.jar:9.0.43]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) [spring-web-5.3.4.jar:5.3.4]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.3.4.jar:5.3.4]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) [tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) [tomcat-embed-core-9.0.43.jar:9.0.43]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) [spring-web-5.3.4.jar:5.3.4]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.3.4.jar:5.3.4]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) [tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) [tomcat-embed-core-9.0.43.jar:9.0.43]
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:93) [spring-boot-actuator-2.4.3.jar:2.4.3]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.3.4.jar:5.3.4]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) [tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) [tomcat-embed-core-9.0.43.jar:9.0.43]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) [spring-web-5.3.4.jar:5.3.4]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.3.4.jar:5.3.4]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) [tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) [tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) [tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) [tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) [tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) [tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) [tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:346) [tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) [tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:887) [tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1684) [tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.43.jar:9.0.43]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_191]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_191]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.43.jar:9.0.43]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_191]
I checked some solutions like this,
#Bean
public RequestInterceptor requestTokenBearerInterceptor() {
return new RequestInterceptor() {
#Override
public void apply(RequestTemplate requestTemplate) {
// OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)
// SecurityContextHolder.getContext().getAuthentication().getDetails();
JwtAuthenticationToken token =
(JwtAuthenticationToken)SecurityContextHolder.getContext().getAuthentication();
String tokenValue = token.getToken().getTokenValue();
requestTemplate.header("Authorization", "bearer " + tokenValue);
}
};
}
Indeed, this solved feign remote call between resource servers(has a access token).
But how can feign access my user service without token?
Thanks for you help.
As i understand the question, you can use the next slice of code in your SecurityConfig file:
.antMatchers(
"/auth/auth/user/list")
.permitAll()
Or, for example, you can use the annotation
#PreAuthorize("permitAll()")
before your #PostMapping method in controller in order to prevent authorization. But you must annotate your SecurityConfig file as following below if you want to try the second variant:
#EnableGlobalMethodSecurity(prePostEnabled = true)

JWT signature does not match locally computed signature. JWT validity cannot be asserted and should not be trusted. Why it is showing me in the log

Utill class
I am trying to use JWT Authentication in my application. Here is my Utli Class
package com.sushovan.jwt.security.jwtutil;
//import java.security.Signature;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
#Service
public class MyJwtUtil {
private String secret = "sushovan";
public <T> T extractClaims(String token, Function<Claims,T> claimResolver) {
final Claims claims = extractAllClaims(token);
return claimResolver.apply(claims);
}
private Claims extractAllClaims(String token) {
return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
}
public String extractUserName(String token) {
return extractClaims(token, Claims::getSubject);
}
public Date extractexpiration(String token) {
return extractClaims(token, Claims::getExpiration);
}
private Boolean isTokenExpired(String token) {
return extractexpiration(token).before(new Date());
}
public String generateToken(String username) {
Map<String,Object> claims = new HashMap<>();
return createToken(claims, username);
}
private String createToken(Map<String, Object> claims, String subject) {
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10))
.signWith(SignatureAlgorithm.HS256, secret).compact();
}
public Boolean validateToken(String token, UserDetails userDetails) {
final String username = extractUserName(token);
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
}
}
Config class
Here is my config class.
package com.sushovan.jwt.security.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.BeanIds;
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;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.sushovan.jwt.security.filter.MyJwtFilter;
#Configuration
#EnableWebSecurity
public class JwtSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private MyJwtFilter myJwtFilter;
#Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(userDetailsService);
provider.setPasswordEncoder(NoOpPasswordEncoder.getInstance());
return provider;
}
#Bean(name = BeanIds.AUTHENTICATION_MANAGER)
#Override
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/authenticate")
.permitAll().anyRequest().authenticated()
.and().exceptionHandling().and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(myJwtFilter, UsernamePasswordAuthenticationFilter.class);
}
}
MyFilter class
Here is my Filter Class
package com.sushovan.jwt.security.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.sushovan.jwt.security.jwtutil.MyJwtUtil;
import com.sushovan.jwt.security.service.CustomUserDetailsservice;
#Component
public class MyJwtFilter extends OncePerRequestFilter {
#Autowired
MyJwtUtil myJwtUtil;
#Autowired
CustomUserDetailsservice service;
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String authorizationToken = request.getHeader("Authorization");
String token = null;
String username = null;
if(authorizationToken != null && authorizationToken.startsWith("Bearer")) {
token = authorizationToken.substring(7);
username = myJwtUtil.extractUserName(token);
}
if(username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = service.loadUserByUsername(username);
if(myJwtUtil.validateToken(token, userDetails)) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
usernamePasswordAuthenticationToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
}
filterChain.doFilter(request, response);
}
}
This is the complete log. I want know the reason why it is showing 'JWT signature does not match locally computed signature. JWT validity cannot be asserted and should not be trusted.' Want to know the root cause of this problem and the solution, how to solve this problem
Here is my complete log . This is the complete log. I want know the reason why it is showing 'JWT signature does not match locally computed signature. JWT validity cannot be asserted and should not be trusted.' Want to know the root cause of this problem and the solution, how to solve this problem
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.7.RELEASE)
2020-05-14 01:34:09.162 INFO 7740 --- [ main] c.s.j.security.DevSecurity1Application : Starting DevSecurity1Application on S-PC with PID 7740 (D:\eclipse-workspace\dev-security-jwt\target\classes started by S in D:\eclipse-workspace\dev-security-jwt)
2020-05-14 01:34:09.214 INFO 7740 --- [ main] c.s.j.security.DevSecurity1Application : No active profile set, falling back to default profiles: default
2020-05-14 01:34:14.639 INFO 7740 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-05-14 01:34:15.058 INFO 7740 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 392ms. Found 1 JPA repository interfaces.
2020-05-14 01:34:19.799 INFO 7740 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 9090 (http)
2020-05-14 01:34:19.943 INFO 7740 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-05-14 01:34:19.944 INFO 7740 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.34]
2020-05-14 01:34:20.789 INFO 7740 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-05-14 01:34:20.790 INFO 7740 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 11291 ms
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
2020-05-14 01:34:21.518 INFO 7740 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-05-14 01:34:21.558 WARN 7740 --- [ main] com.zaxxer.hikari.util.DriverDataSource : Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation.
2020-05-14 01:34:24.934 INFO 7740 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-05-14 01:34:25.652 INFO 7740 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-05-14 01:34:26.564 INFO 7740 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.15.Final
2020-05-14 01:34:28.995 INFO 7740 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-05-14 01:34:29.874 INFO 7740 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
2020-05-14 01:34:34.489 INFO 7740 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-05-14 01:34:34.512 INFO 7740 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-05-14 01:34:35.815 WARN 7740 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-05-14 01:34:36.842 INFO 7740 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#2ba9f986, org.springframework.security.web.context.SecurityContextPersistenceFilter#3d512652, org.springframework.security.web.header.HeaderWriterFilter#23ea8830, org.springframework.security.web.authentication.logout.LogoutFilter#49038f97, com.sushovan.jwt.security.filter.MyJwtFilter#718989fa, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#3b96f8b0, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#5dfc2a4, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#4aa3fc9a, org.springframework.security.web.session.SessionManagementFilter#44da7eb3, org.springframework.security.web.access.ExceptionTranslationFilter#2b9aeedb, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#4d0e1a9a]
2020-05-14 01:34:37.382 INFO 7740 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-05-14 01:34:38.753 INFO 7740 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 9090 (http) with context path ''
2020-05-14 01:34:38.757 INFO 7740 --- [ main] c.s.j.security.DevSecurity1Application : Started DevSecurity1Application in 33.709 seconds (JVM running for 37.509)
2020-05-14 01:34:54.392 INFO 7740 --- [nio-9090-exec-4] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-05-14 01:34:54.394 INFO 7740 --- [nio-9090-exec-4] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-05-14 01:34:54.469 INFO 7740 --- [nio-9090-exec-4] o.s.web.servlet.DispatcherServlet : Completed initialization in 75 ms
2020-05-14 01:34:55.200 ERROR 7740 --- [nio-9090-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
io.jsonwebtoken.SignatureException: JWT signature does not match locally computed signature. JWT validity cannot be asserted and should not be trusted.
at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:354) ~[jjwt-0.9.1.jar:0.9.1]
at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:481) ~[jjwt-0.9.1.jar:0.9.1]
at io.jsonwebtoken.impl.DefaultJwtParser.parseClaimsJws(DefaultJwtParser.java:541) ~[jjwt-0.9.1.jar:0.9.1]
at com.sushovan.jwt.security.jwtutil.MyJwtUtil.extractAllClaims(MyJwtUtil.java:29) ~[classes/:na]
at com.sushovan.jwt.security.jwtutil.MyJwtUtil.extractClaims(MyJwtUtil.java:23) ~[classes/:na]
at com.sushovan.jwt.security.jwtutil.MyJwtUtil.extractUserName(MyJwtUtil.java:33) ~[classes/:na]
at com.sushovan.jwt.security.filter.MyJwtFilter.doFilterInternal(MyJwtFilter.java:40) ~[classes/:na]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) ~[spring-security-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92) ~[spring-security-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77) ~[spring-security-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) ~[spring-security-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) ~[spring-security-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) ~[spring-security-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) ~[spring-security-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) [tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) [tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) [tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.34.jar:9.0.34]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_251]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_251]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.34.jar:9.0.34]
at java.lang.Thread.run(Unknown Source) [na:1.8.0_251]
.setSigningKey(Base64.getEncoder().encodeToString("you signing key value"))
Please try this hope it works.

Getting NPE while receiving the reply message using RabbitTemplate

I have two microservices. one contains the REST controller which has the Get method which receives the message when sent to specific queue. other microservice just sends the reply message to same queue so that processed message can be seen in the browser when hit the REST API
however, getting NPE while receiving the message.
below is the complete stack-trace:
2018-05-19 15:46:13.409 INFO 30104 --- [nio-8097-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/unit] : Initializing Spring FrameworkServlet 'dispatcherServlet' 2018-05-19 15:46:13.409 INFO 30104 --- [nio-8097-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started 2018-05-19 15:46:13.443 INFO 30104 --- [nio-8097-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 34 ms 2018-05-19 15:46:13.533 INFO 30104 --- [nio-8097-exec-1] o.s.a.r.c.CachingConnectionFactory : Attempting to connect to: [35.154.27.134:5672] 2018-05-19 15:46:13.593 INFO 30104 --- [nio-8097-exec-1] o.s.a.r.c.CachingConnectionFactory : Created new connection: rabbitConnectionFactory#5b2b49d6:0/SimpleConnection#3e4f13fa [delegate=amqp://guest#35.154.27.134:5672/, localPort= 58742] 2018-05-19 15:46:18.681 ERROR 30104 --- [nio-8097-exec-1] o.a.c.c.C.[.[.[.[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [/unit] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException: null
at com.infy.ci.unitamqpservice.UnitAmqpRestController.getAggregatedDataForSectionOfNightlyBuild(UnitAmqpRestController.java:83) ~[classes!/:0.0.1-SNAPSHOT]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_151]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_151]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_151]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_151]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) ~[spring-webmvc-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) ~[spring-webmvc-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) ~[spring-webmvc-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) ~[spring-webmvc-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.27.jar!/:8.5.27]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108) ~[spring-web-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.14.RELEASE.jar!/:4.3.14.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) ~[tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504) [tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) [tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) [tomcat-embed-core-8.5.27.jar!/:8.5.27]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.27.jar!/:8.5.27]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_151]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_151]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.27.jar!/:8.5.27]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_151]
further, when hitting the REST API in the web browser, getting following log on the console
2018-05-19 15:45:22.328 INFO 30023 --- [ main]
o.s.j.e.a.AnnotationMBeanExporter : Located managed bean
'rabbitConnectionFactory': registering with JMX server as MBean
[org.springframework.amqp.rabbit.connection:name=rabbitConnectionFactory,type=CachingConnectionFactory]
2018-05-19 15:45:22.423 INFO 30023 --- [ main]
o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase
2147483647 2018-05-19 15:45:22.445 INFO 30023 --- [cTaskExecutor-1]
o.s.a.r.c.CachingConnectionFactory : Attempting to connect to:
[35.154.27.134:5672] 2018-05-19 15:45:22.471 INFO 30023 ---
[cTaskExecutor-1] o.s.a.r.c.CachingConnectionFactory : Created
new connection:
rabbitConnectionFactory#325fc787:0/SimpleConnection#38a7acf7
[delegate=amqp://guest#35.154.27.134:5672/, localPort= 58736]
2018-05-19 15:45:22.875 INFO 30023 --- [ main]
s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s):
8099 (http) 2018-05-19 15:45:22.902 INFO 30023 --- [ main]
com.infy.ci.unitdbamqpservice.RPCServer : Started RPCServer in 7.517
seconds (JVM running for 8.286) Sat May 19 15:45:23 UTC 2018 WARN:
Establishing SSL connection without server's identity verification is
not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+
requirements SSL connection must be established by default if explicit
option isn't set. For compliance with existing applications not using
SSL the verifyServerCertificate property is set to 'false'. You need
either to explicitly disable SSL by setting useSSL=false, or set
useSSL=true and provide truststore for server certificate
verification. Sat May 19 15:46:13 UTC 2018 WARN: Establishing SSL
connection without server's identity verification is not recommended.
According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL
connection must be established by default if explicit option isn't
set. For compliance with existing applications not using SSL the
verifyServerCertificate property is set to 'false'. You need either to
explicitly disable SSL by setting useSSL=false, or set useSSL=true and
provide truststore for server certificate verification.
can this be the reason for NPE ? i have already included following in the JDBC code but still no luck.
prop.setProperty("useSSL", "false");
prop.setProperty("autoReconnect", "true");
both the services are checked-in at github:
https://github.com/irfanjs/unitamqpservice
https://github.com/irfanjs/unitdbamqpservice
return rabbitTemplate.convertSendAndReceive("myExchange", requestQueueName, message).toString();
You are unconditionally calling toString() on the reply.
The reply will be null if the template's replyTimeout is exceeded before the reply is received (the timeout defaults to 5 seconds).
You must check for null result before calling toString().
just sends the reply message to same queue
You can't send the reply to the same queue - it must go to the replyTo header in the request.
If you use a #RabbitListener or MessageListenerAdapter on the server side, it will be taken care of for you.
This has nothing to do with SSL
WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set.
That warning is about MySQL.
EDIT
I just hacked your applications down to the bare minimum and they work fine for me...
#Controller
#Configuration
#PropertySource("classpath:/application.properties")
#RequestMapping("/unittestdata")
public class UnitAmqpRestController {
private final String requestQueueName = "rpc_queue1";
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
private final Logger logger = LoggerFactory.getLogger(UnitAmqpRestController.class);
private final RabbitTemplate rabbitTemplate;
#Autowired
public UnitAmqpRestController(RabbitTemplate rabbitTemplate) {
this.rabbitTemplate = rabbitTemplate;
rabbitTemplate.setReplyTimeout(15_000L);
}
#RequestMapping(value = "/{projectid}/ut/aggregate",
method = RequestMethod.GET,
produces = MediaType.TEXT_HTML_VALUE)
public #ResponseBody String getAggregatedDataForSectionOfNightlyBuild(#PathVariable("projectid") int projectid,
#RequestParam("buildtype") String buildtype, #RequestParam("build") String build) throws Exception {
if (build.toLowerCase().equals("latest") && buildtype.equals("nightly")) {
String message = String.format("aggregate");
logger.info("Sending: " + message);
Object returned = rabbitTemplate.convertSendAndReceive("", requestQueueName, message);
logger.info("Reply: " + returned);
if (returned == null) {
throw new RuntimeException("failed to get a response");
}
return returned.toString();
}
else {
return null;
}
}
}
and
#Configuration
#SpringBootApplication
#PropertySource("classpath:/application.properties")
public class RPCServer {
private static final Logger logger = LoggerFactory.getLogger(RPCServer.class);
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
SpringApplication.run(RPCServer.class, args);
}
private static final String RPC_QUEUE_NAME = "rpc_queue1";
#Bean
public Queue queue() {
return new Queue(RPC_QUEUE_NAME);
}
#Component
public static class RpcListener {
#RabbitListener(queues = RPC_QUEUE_NAME)
public String reply(String request) throws IOException, TimeoutException, ClassNotFoundException, SQLException {
logger.info(request);
return request.toUpperCase();
}
}
}
and
2018-05-20 12:46:00.298 INFO 13369 --- [nio-8097-exec-1] c.i.c.u.UnitAmqpRestController : Sending: aggregate
...
o.s.amqp.rabbit.core.RabbitTemplate : Publishing message on exchange [], routingKey = [rpc_queue1]
2018-05-20 12:46:00.554 DEBUG 13369 --- [nio-8097-exec-1] o.s.amqp.rabbit.core.RabbitTemplate : Reply: (Body:'AGGREGATE' MessageProperties [headers={}, timestamp=null, messageId=null, userId=null, receivedUserId=null, appId=null, clusterId=null, type=null, correlationId=null, correlationIdString=null, replyTo=null, contentType=text/plain, contentEncoding=UTF-8, contentLength=0, deliveryMode=null, receivedDeliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=, receivedRoutingKey=amq.rabbitmq.reply-to.g2dkABByYWJiaXRAbG9jYWxob3N0AAAHFAAAAAAC.3M1LyvOdR9dHQehSV4l67A==, receivedDelay=null, deliveryTag=1, messageCount=null, consumerTag=null, consumerQueue=null])
2018-05-20 12:46:00.561 INFO 13369 --- [nio-8097-exec-1] c.i.c.u.UnitAmqpRestController : Reply: AGGREGATE

spring security 5 prints trace Exception for oauth2 bad credentials

For Oauth2+jwt running on springboot, I've successfully implemented with spring4.
However, when I tried to upgrade it to spring5 (springboot2), whenever the user inputs the wrong account/password, the "Bad Credential" Exception was not caught by spring5. It will be printed with the traced exception to the log.
I've uploaded the code to github: https://github.com/ShanGor/springboot-jwt
I've raised an issue to the project:
https://github.com/spring-projects/spring-security/issues/4933
2017-12-29 10:06:13.168 INFO 8152 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-12-29 10:06:13.917 INFO 8152 --- [ restartedMain] .s.o.p.e.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)
2017-12-29 10:06:13.917 INFO 8152 --- [ restartedMain] .s.o.p.e.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)
2017-12-29 10:06:13.918 INFO 8152 --- [ restartedMain] .s.o.p.e.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
2017-12-29 10:06:13.918 INFO 8152 --- [ restartedMain] .s.o.p.e.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
2017-12-29 10:06:13.919 INFO 8152 --- [ restartedMain] .s.o.p.e.FrameworkEndpointHandlerMapping : Mapped "{[/oauth/check_token]}" onto public java.util.Map<java.lang.String, ?> org.springframework.security.oauth2.provider.endpoint.CheckTokenEndpoint.checkToken(java.lang.String)
2017-12-29 10:06:13.919 INFO 8152 --- [ restartedMain] .s.o.p.e.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
2017-12-29 10:06:13.919 INFO 8152 --- [ restartedMain] .s.o.p.e.FrameworkEndpointHandlerMapping : Mapped "{[/oauth/error]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.security.oauth2.provider.endpoint.WhitelabelErrorEndpoint.handleError(javax.servlet.http.HttpServletRequest)
2017-12-29 10:06:13.922 INFO 8152 --- [ restartedMain] .s.o.p.e.FrameworkEndpointHandlerMapping : Mapped "{[/oauth/token_key],methods=[GET]}" onto public java.util.Map<java.lang.String, java.lang.String> org.springframework.security.oauth2.provider.endpoint.TokenKeyEndpoint.getKey(java.security.Principal)
2017-12-29 10:06:14.425 INFO 8152 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/oauth/token'], Ant [pattern='/oauth/token_key'], Ant [pattern='/oauth/check_token']]], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#4c3c304c, org.springframework.security.web.context.SecurityContextPersistenceFilter#b0534cb, org.springframework.security.web.header.HeaderWriterFilter#7ca9ea3e, org.springframework.security.web.authentication.logout.LogoutFilter#6440ffc8, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#7a7907db, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#6c57abd9, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#58d97e65, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#537b4e05, org.springframework.security.web.session.SessionManagementFilter#3640cf55, org.springframework.security.web.access.ExceptionTranslationFilter#48e05dfe, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#59b25dc3]
2017-12-29 10:06:14.436 INFO 8152 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfiguration$NotOAuthRequestMatcher#488e38a4, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#23c39a0c, org.springframework.security.web.context.SecurityContextPersistenceFilter#7cee62ba, org.springframework.security.web.header.HeaderWriterFilter#6c845ecf, org.springframework.security.web.authentication.logout.LogoutFilter#4f048143, org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter#f13ab77, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#3cfa8985, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#7246caf3, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#524a9adb, org.springframework.security.web.session.SessionManagementFilter#74292ac2, org.springframework.security.web.access.ExceptionTranslationFilter#45d0a092, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#2c85c82e]
2017-12-29 10:06:14.438 INFO 8152 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher#1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#35758726, org.springframework.security.web.context.SecurityContextPersistenceFilter#4a8bb2ae, org.springframework.security.web.header.HeaderWriterFilter#2b3471d8, org.springframework.security.web.authentication.logout.LogoutFilter#11e2fcb8, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#6eb22e8, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#79a9509b, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#711b44c7, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#1e63d033, org.springframework.security.web.session.SessionManagementFilter#5526a7e3, org.springframework.security.web.access.ExceptionTranslationFilter#3fc18a1e]
2017-12-29 10:06:14.439 WARN 8152 --- [ restartedMain] o.s.s.c.a.web.builders.WebSecurity :
********************************************************************
********** Security debugging is enabled. *************
********** This may include sensitive information. *************
********** Do not use in a production system! *************
********************************************************************
2017-12-29 10:06:14.726 INFO 8152 --- [ restartedMain] o.h.v.i.engine.ValidatorFactoryImpl : HV000238: Temporal validation tolerance set to 0.
2017-12-29 10:06:14.918 INFO 8152 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#7854ea4: startup date [Fri Dec 29 10:06:08 CST 2017]; root of context hierarchy
2017-12-29 10:06:14.972 WARN 8152 --- [ restartedMain] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2017-12-29 10:06:14.997 INFO 8152 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/springjwt/cities]}" onto public java.util.List<tech.comfortheart.oauth.jwt.model.domain.RandomCity> tech.comfortheart.oauth.jwt.controller.ResourceController.getUser()
2017-12-29 10:06:14.998 INFO 8152 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/springjwt/users],methods=[GET]}" onto public java.util.List<tech.comfortheart.oauth.jwt.model.domain.User> tech.comfortheart.oauth.jwt.controller.ResourceController.getUsers()
2017-12-29 10:06:15.001 INFO 8152 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-12-29 10:06:15.001 INFO 8152 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-12-29 10:06:15.059 INFO 8152 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-29 10:06:15.059 INFO 8152 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-29 10:06:15.112 INFO 8152 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-29 10:06:15.333 INFO 8152 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2017-12-29 10:06:15.392 INFO 8152 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-12-29 10:06:15.393 INFO 8152 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'dataSource' has been autodetected for JMX exposure
2017-12-29 10:06:15.399 INFO 8152 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
2017-12-29 10:06:15.511 INFO 8152 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2017-12-29 10:06:15.517 INFO 8152 --- [ restartedMain] t.c.oauth.jwt.SpringbootJwtApplication : Started SpringbootJwtApplication in 7.375 seconds (JVM running for 9.298)
2017-12-29 10:06:20.580 INFO 8152 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-12-29 10:06:20.580 INFO 8152 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2017-12-29 10:06:20.620 INFO 8152 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 40 ms
2017-12-29 10:06:20.628 INFO 8152 --- [nio-8080-exec-1] Spring Security Debugger :
************************************************************
Request received for POST '/oauth/token':
org.apache.catalina.connector.RequestFacade#191b82f2
servletPath:/oauth/token
pathInfo:null
headers:
host: localhost:8080
authorization: Basic dGVzdGp3dGNsaWVudGlkOlhZN2ttem9OemwxMDA=
user-agent: curl/7.46.0
accept: */*
content-length: 55
content-type: application/x-www-form-urlencoded
Security filter chain: [
WebAsyncManagerIntegrationFilter
SecurityContextPersistenceFilter
HeaderWriterFilter
LogoutFilter
BasicAuthenticationFilter
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
AnonymousAuthenticationFilter
SessionManagementFilter
ExceptionTranslationFilter
FilterSecurityInterceptor
]
************************************************************
2017-12-29 10:06:20.684 INFO 8152 --- [nio-8080-exec-1] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
2017-12-29 10:06:20.818 ERROR 8152 --- [nio-8080-exec-1] o.s.s.o.provider.endpoint.TokenEndpoint : Handling error: InvalidGrantException, Bad credentials
org.springframework.security.oauth2.common.exceptions.InvalidGrantException: Bad credentials
at org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter.getOAuth2Authentication(ResourceOwnerPasswordTokenGranter.java:79) ~[spring-security-oauth2-2.2.1.RELEASE.jar:na]
at org.springframework.security.oauth2.provider.token.AbstractTokenGranter.getAccessToken(AbstractTokenGranter.java:70) ~[spring-security-oauth2-2.2.1.RELEASE.jar:na]
at org.springframework.security.oauth2.provider.token.AbstractTokenGranter.grant(AbstractTokenGranter.java:65) ~[spring-security-oauth2-2.2.1.RELEASE.jar:na]
at org.springframework.security.oauth2.provider.CompositeTokenGranter.grant(CompositeTokenGranter.java:38) ~[spring-security-oauth2-2.2.1.RELEASE.jar:na]
at org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer$4.grant(AuthorizationServerEndpointsConfigurer.java:561) ~[spring-security-oauth2-2.2.1.RELEASE.jar:na]
at org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(TokenEndpoint.java:132) ~[spring-security-oauth2-2.2.1.RELEASE.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_66]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_66]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_66]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_66]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:871) ~[spring-webmvc-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:777) ~[spring-webmvc-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978) [spring-webmvc-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:881) [spring-webmvc-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855) [spring-webmvc-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-embed-websocket-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:215) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.security.web.debug.DebugFilter.invokeWithWrappedRequest(DebugFilter.java:90) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.security.web.debug.DebugFilter.doFilter(DebugFilter.java:77) [spring-security-web-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) [spring-web-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) [spring-web-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108) [spring-web-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) [spring-web-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) [spring-web-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96) [spring-web-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.2.RELEASE.jar:5.0.2.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.23.jar:8.5.23]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_66]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_66]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.23.jar:8.5.23]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_66]
2017-12-29 10:06:20.893 WARN 8152 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Resolved exception caused by Handler execution: error="invalid_grant", error_description="Bad credentials"
try add this to AuthorizationServerConfig ...if password is not encoded...otherwise use the correct password encoder...
#Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.passwordEncoder(passwordEncoder());
}
#Bean
public PasswordEncoder passwordEncoder() {
PasswordEncoder encoder = NoOpPasswordEncoder.getInstance();
return encoder;
}

Spring Security's #PreAuthorize causes 415 "Unsupported Media Type" error

I'm using Spring Boot, Spring Data JPA, Spring Data REST and Spring Security via Java Config in my application. I'm trying to add this #PreAuthorize annotation to the below method in my UserPrefsRESTController.
Interface:
package com.company.services.rest;
import com.company.server.model.user.preferences.UserPrefs;
import com.company.server.user.prefs.UserPrefsDTO;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
#RequestMapping("/api/userprefs")
public interface UserPrefsRESTController {
#RequestMapping(method = RequestMethod.POST, produces = "application/json")
#PreAuthorize("#userPrefs.id == principal.username or hasRole('ADMIN')")
ResponseEntity<UserPrefsDTO> setUserPrefs(#RequestBody UserPrefs userPrefs);
#RequestMapping(method = RequestMethod.GET, produces = "application/json")
ResponseEntity<UserPrefsDTO> getUserPrefs(#RequestParam String id);
}
Implementation class:
package com.company.services.rest;
import com.company.server.model.user.preferences.UserPrefs;
import com.company.server.user.prefs.UserPrefsDTO;
import com.company.server.user.prefs.UserPrefsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class UserPrefsRESTControllerImpl implements UserPrefsRESTController {
#Autowired
private UserPrefsService userPrefsService;
#Override
public ResponseEntity<UserPrefsDTO> setUserPrefs(UserPrefs userPrefs) {
UserPrefsDTO response;
try {
response = userPrefsService.setUserPrefsValue(userPrefs);
} catch (final IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
}
return ResponseEntity.ok(response);
}
#Override
public ResponseEntity<UserPrefsDTO> getUserPrefs(String id) {
return ResponseEntity.ok(userPrefsService.getUserPrefs(id));
}
}
The endpoint properly returns the UserPrefsDTO when the annotation is not present, but when I add the annotation I get the following error
{
"timestamp": 1494518855146,
"status": 415,
"error": "Unsupported Media Type",
"exception": "org.springframework.web.HttpMediaTypeNotSupportedException",
"message": "Unsupported Media Type",
"path": "/api/userprefs"
}
I tried changing the annotation to an #PostAuthorize as well and I get the same error and do not hit my breakpoints inside the method so it's something to do with the fact that the annotation is there rather than it being #PreAuthorize specifically. I also tried several other expressions including just role checking and permitAll() and get the same results. All authenticated requests return the error regardless of whether the authenticated user is an admin, the relevant user (that matches #userPrefs.id == principal.username) or another user. I also tried removing produces = "application/json" from the #RequestMapping; and adding consumes = "application/json". Both to no avail
Here is the other relevant code
UserPrefsDTO:
package com.company.server.user.prefs;
import java.io.Serializable;
public class UserPrefsDTO implements Serializable{
private String id;
private String value;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Configuration:
package com.company.spring.boot;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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
#EnableGlobalMethodSecurity(prePostEnabled = true)
#EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.withUser("runuser").password("password").roles("USER", "RUN").and()
.withUser("admin").password("password").roles("USER", "RUN", "ADMIN");
}
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin().permitAll().and()
.logout().permitAll().and()
.authorizeRequests()
.anyRequest().authenticated()
.and().csrf().disable()
.httpBasic();
}
}
UserPrefsRepository:
package com.company.server.model.repositories;
import com.company.server.model.ModelConstants;
import com.company.server.model.user.preferences.UserPrefs;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import javax.persistence.PersistenceContext;
#PersistenceContext(name = ModelConstants.DOMAIN_ID)
#RepositoryRestResource(collectionResourceRel = "UserPrefs", path = "UserPrefs", itemResourceRel="UserPrefs")
public interface UserPrefsRepository extends JpaRepository<UserPrefs, String> {
#Override
#PreAuthorize("hasRole('ADMIN')")
Page<UserPrefs> findAll(Pageable pageable);
#PostAuthorize("returnObject != null && returnObject.id == principal.username or hasRole('ADMIN')")
UserPrefs findById(#Param("id") String id);
}
Strangely enough, I am successfully using the same annotation in an event handler that I'm using to catch requests to the Spring Data REST generated endpoints for the UserPrefs object
UserPrefsEventHandler:
package com.company.server.model.user.preferences;
import org.springframework.data.rest.core.annotation.HandleBeforeCreate;
import org.springframework.data.rest.core.annotation.HandleBeforeDelete;
import org.springframework.data.rest.core.annotation.HandleBeforeSave;
import org.springframework.data.rest.core.annotation.RepositoryEventHandler;
import org.springframework.security.access.prepost.PreAuthorize;
#RepositoryEventHandler
#SuppressWarnings("unused")
public class UserPrefsEventHandler {
#HandleBeforeCreate
#PreAuthorize("#userPrefs.id == principal.username or hasRole('ADMIN')")
public void checkCreateAuthority(UserPrefs userPrefs) {
System.out.println("checkCreateAuthority");
}
#HandleBeforeSave
#PreAuthorize("#userPrefs.id == principal.username or hasRole('ADMIN')")
public void checkUpdateAuthority(UserPrefs userPrefs) {
System.out.println("checkUpdateAuthority");
}
#HandleBeforeDelete
#PreAuthorize("hasRole('ADMIN')")
public void checkDeleteAuthority(UserPrefs userPrefs) {
System.out.println("checkDeleteAuthority");
}
}
Note: The above class is being added via a bean in another config file:
#Bean
UserPrefsEventHandler userPrefsEventHandler() {
return new UserPrefsEventHandler();
}
What is causing the 415 error?
Update - Spring Security debug logs:
2017-05-11 11:51:18.784 DEBUG 10256 --- [qtp424848797-87] o.s.security.web.FilterChainProxy : /api/userprefs at position 1 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2017-05-11 11:51:18.786 DEBUG 10256 --- [qtp424848797-87] o.s.security.web.FilterChainProxy : /api/userprefs at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2017-05-11 11:51:18.787 DEBUG 10256 --- [qtp424848797-87] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
2017-05-11 11:51:18.787 DEBUG 10256 --- [qtp424848797-87] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created.
2017-05-11 11:51:18.790 DEBUG 10256 --- [qtp424848797-87] o.s.security.web.FilterChainProxy : /api/userprefs at position 3 of 13 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2017-05-11 11:51:18.790 DEBUG 10256 --- [qtp424848797-87] o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#27192c6
2017-05-11 11:51:18.790 DEBUG 10256 --- [qtp424848797-87] o.s.security.web.FilterChainProxy : /api/userprefs at position 4 of 13 in additional filter chain; firing Filter: 'LogoutFilter'
2017-05-11 11:51:18.790 DEBUG 10256 --- [qtp424848797-87] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', GET]
2017-05-11 11:51:18.791 DEBUG 10256 --- [qtp424848797-87] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'POST /api/userprefs' doesn't match 'GET /logout
2017-05-11 11:51:18.791 DEBUG 10256 --- [qtp424848797-87] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', POST]
2017-05-11 11:51:18.791 DEBUG 10256 --- [qtp424848797-87] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/api/userprefs'; against '/logout'
2017-05-11 11:51:18.791 DEBUG 10256 --- [qtp424848797-87] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', PUT]
2017-05-11 11:51:18.791 DEBUG 10256 --- [qtp424848797-87] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'POST /api/userprefs' doesn't match 'PUT /logout
2017-05-11 11:51:18.791 DEBUG 10256 --- [qtp424848797-87] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', DELETE]
2017-05-11 11:51:18.791 DEBUG 10256 --- [qtp424848797-87] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'POST /api/userprefs' doesn't match 'DELETE /logout
2017-05-11 11:51:18.791 DEBUG 10256 --- [qtp424848797-87] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2017-05-11 11:51:18.791 DEBUG 10256 --- [qtp424848797-87] o.s.security.web.FilterChainProxy : /api/userprefs at position 5 of 13 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2017-05-11 11:51:18.792 DEBUG 10256 --- [qtp424848797-87] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/api/userprefs'; against '/login'
2017-05-11 11:51:18.792 DEBUG 10256 --- [qtp424848797-87] o.s.security.web.FilterChainProxy : /api/userprefs at position 6 of 13 in additional filter chain; firing Filter: 'DefaultLoginPageGeneratingFilter'
2017-05-11 11:51:18.792 DEBUG 10256 --- [qtp424848797-87] o.s.security.web.FilterChainProxy : /api/userprefs at position 7 of 13 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
2017-05-11 11:51:18.794 DEBUG 10256 --- [qtp424848797-87] o.s.s.w.a.www.BasicAuthenticationFilter : Basic Authentication Authorization header found for user 'admin'
2017-05-11 11:51:18.795 DEBUG 10256 --- [qtp424848797-87] o.s.s.authentication.ProviderManager : Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
2017-05-11 11:51:18.802 DEBUG 10256 --- [qtp424848797-87] o.s.s.w.a.www.BasicAuthenticationFilter : Authentication success: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#e0123f1f: 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_RUN,ROLE_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: ROLE_ADMIN, ROLE_RUN, ROLE_USER
2017-05-11 11:51:18.802 DEBUG 10256 --- [qtp424848797-87] o.s.security.web.FilterChainProxy : /api/userprefs at position 8 of 13 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2017-05-11 11:51:18.802 DEBUG 10256 --- [qtp424848797-87] o.s.security.web.FilterChainProxy : /api/userprefs at position 9 of 13 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2017-05-11 11:51:18.804 DEBUG 10256 --- [qtp424848797-87] o.s.security.web.FilterChainProxy : /api/userprefs at position 10 of 13 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2017-05-11 11:51:18.804 DEBUG 10256 --- [qtp424848797-87] o.s.s.w.a.AnonymousAuthenticationFilter : SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken#e0123f1f: 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_RUN,ROLE_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: ROLE_ADMIN, ROLE_RUN, ROLE_USER'
2017-05-11 11:51:18.804 DEBUG 10256 --- [qtp424848797-87] o.s.security.web.FilterChainProxy : /api/userprefs at position 11 of 13 in additional filter chain; firing Filter: 'SessionManagementFilter'
2017-05-11 11:51:18.804 DEBUG 10256 --- [qtp424848797-87] s.CompositeSessionAuthenticationStrategy : Delegating to org.springframework.security.web.authentication.session.ChangeSessionIdAuthenticationStrategy#419074cb
2017-05-11 11:51:18.806 DEBUG 10256 --- [qtp424848797-87] w.c.HttpSessionSecurityContextRepository : HttpSession being created as SecurityContext is non-default
2017-05-11 11:51:18.810 DEBUG 10256 --- [qtp424848797-87] w.c.HttpSessionSecurityContextRepository : SecurityContext 'org.springframework.security.core.context.SecurityContextImpl#e0123f1f: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#e0123f1f: 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_RUN,ROLE_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: ROLE_ADMIN, ROLE_RUN, ROLE_USER' stored to HttpSession: 'org.eclipse.jetty.server.session.Session#6c5d0309
2017-05-11 11:51:18.811 DEBUG 10256 --- [qtp424848797-87] o.s.security.web.FilterChainProxy : /api/userprefs at position 12 of 13 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2017-05-11 11:51:18.811 DEBUG 10256 --- [qtp424848797-87] o.s.security.web.FilterChainProxy : /api/userprefs at position 13 of 13 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2017-05-11 11:51:18.811 DEBUG 10256 --- [qtp424848797-87] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', GET]
2017-05-11 11:51:18.811 DEBUG 10256 --- [qtp424848797-87] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'POST /api/userprefs' doesn't match 'GET /logout
2017-05-11 11:51:18.812 DEBUG 10256 --- [qtp424848797-87] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', POST]
2017-05-11 11:51:18.812 DEBUG 10256 --- [qtp424848797-87] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/api/userprefs'; against '/logout'
2017-05-11 11:51:18.812 DEBUG 10256 --- [qtp424848797-87] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', PUT]
2017-05-11 11:51:18.812 DEBUG 10256 --- [qtp424848797-87] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'POST /api/userprefs' doesn't match 'PUT /logout
2017-05-11 11:51:18.812 DEBUG 10256 --- [qtp424848797-87] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', DELETE]
2017-05-11 11:51:18.812 DEBUG 10256 --- [qtp424848797-87] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'POST /api/userprefs' doesn't match 'DELETE /logout
2017-05-11 11:51:18.812 DEBUG 10256 --- [qtp424848797-87] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2017-05-11 11:51:18.812 DEBUG 10256 --- [qtp424848797-87] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /api/userprefs; Attributes: [authenticated]
2017-05-11 11:51:18.812 DEBUG 10256 --- [qtp424848797-87] o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#e0123f1f: 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_RUN,ROLE_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: ROLE_ADMIN, ROLE_RUN, ROLE_USER
2017-05-11 11:51:18.818 DEBUG 10256 --- [qtp424848797-87] o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.web.access.expression.WebExpressionVoter#721d7b2d, returned: 1
2017-05-11 11:51:18.819 DEBUG 10256 --- [qtp424848797-87] o.s.s.w.a.i.FilterSecurityInterceptor : Authorization successful
2017-05-11 11:51:18.819 DEBUG 10256 --- [qtp424848797-87] o.s.s.w.a.i.FilterSecurityInterceptor : RunAsManager did not change Authentication object
2017-05-11 11:51:18.819 DEBUG 10256 --- [qtp424848797-87] o.s.security.web.FilterChainProxy : /api/userprefs reached end of additional filter chain; proceeding with original chain
2017-05-11 11:51:18.868 DEBUG 10256 --- [qtp424848797-87] w.c.HttpSessionSecurityContextRepository : SecurityContext 'org.springframework.security.core.context.SecurityContextImpl#e0123f1f: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#e0123f1f: 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_RUN,ROLE_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: ROLE_ADMIN, ROLE_RUN, ROLE_USER' stored to HttpSession: 'org.eclipse.jetty.server.session.Session#6c5d0309
2017-05-11 11:51:18.916 DEBUG 10256 --- [qtp424848797-87] o.s.s.w.a.ExceptionTranslationFilter : Chain processed normally
2017-05-11 11:51:18.917 DEBUG 10256 --- [qtp424848797-87] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
Strangely I don't see anything related to the error in the debug logs, though I could be overlooking something.
Update 2 - "multipart/form-data" vs "application/json"
I have been submitting the request as "multipart/form-data" which is generating the error. When I instead send it as "application/json" the request succeeds. I am still puzzled by the fact that the request works fine when submitting as "multipart/form-data" when the #PreAuthorize annotation is not present. While sending as "application/json" is a sufficient solution to my problem, the question remains as to why this is an issue.

Resources