Grails spring security custom session authentication - rest

I work on a legacy system and as a result can't follow the box standard documentation given with the Spring Security Core plugin (documentation), which means I don't have fancy to domain objects.
What I am trying to develop is a REST-API in grails with session based authentication (cannot use basic auth as the front end is Angular, and needs to be able to invalidate a user after 30 mins of inactivity)
I have found a resource which is doing what I am trying to do - although that is using domain objects, which is where I am running short.
The grails app will also end up on a Tomcat server so will have to be compatible with that too.
However, I have tried to make my own authentication provider. I have the following in application.groovy:
grails.plugin.springsecurity.providerNames = ['myAuthenticator','daoAuthenticationProvider']
grails.plugin.springsecurity.rest.login.endpointUrl = '/login'
grails.plugin.springsecurity.filterChain.chainMap = [
[pattern:'/login', filters: 'JOINED_FILTERS,-anonymousAuthenticationFilter,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter,-rememberMeAuthenticationFilter'],
[pattern: '/assets/**', filters: 'none'],
[pattern: '/**/js/**', filters: 'none'],
[pattern: '/**/css/**', filters: 'none'],
[pattern: '/**/images/**', filters: 'none'],
[pattern: '/**/favicon.ico', filters: 'none']//,
[pattern: '/**', filters: 'JOINED_FILTERS,-anonymousAuthenticationFilter,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter,-rememberMeAuthenticationFilter']
]
In the resources.groovy I have
beans = {
myAuthenticator(MyAuthenticator)
}
My MyAuthenticator class:
class MyAuthenticator implements AuthenticationProvider {
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
ArrayList<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<SimpleGrantedAuthority>();
simpleGrantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"))
return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), simpleGrantedAuthorities)
}
#Override
public boolean supports(Class<?> authentication) {
return (authentication == UsernamePasswordAuthenticationToken.class);
}
}
To test whether or not this works I am firing off a CURL.
curl -i -H "Content-Type: application/json" --data '{"username":"user","password":"pass"}' http://localhost:8080/login
Which returns a 401. The stacktrace from the log is as following:
DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/login'; against '/login'
DEBUG o.s.security.web.FilterChainProxy - /login at position 1 of 9 in additional filter chain; firing Filter: 'SecurityRequestHolderFilter'
DEBUG o.s.security.web.FilterChainProxy - /login at position 2 of 9 in additional filter chain; firing Filter: 'MutableLogoutFilter'
DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/login'; against '/logoff'
DEBUG o.s.security.web.FilterChainProxy - /login at position 3 of 9 in additional filter chain; firing Filter: 'RestAuthenticationFilter'
DEBUG g.p.s.rest.RestAuthenticationFilter - Actual URI is /login; endpoint URL is /login
DEBUG g.p.s.rest.RestAuthenticationFilter - Applying authentication filter to this request
DEBUG g.p.s.r.c.DefaultJsonPayloadCredentialsExtractor - Extracted credentials from JSON payload. Username: user,password: [PROTECTED]
DEBUG g.p.s.rest.RestAuthenticationFilter - Trying to authenticate the request
DEBUG o.s.s.authentication.ProviderManager - Authentication attempt using MyAuthenticator
DEBUG g.p.s.rest.RestAuthenticationFilter - Request authenticated. Storing the authentication result in the security context
DEBUG g.p.s.rest.RestAuthenticationFilter - Authentication result: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#4095914d: Principal: 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
DEBUG g.p.s.r.t.g.j.AbstractJwtTokenGenerator - Generating an access token with default expiration: 3600
DEBUG g.p.s.r.t.g.j.AbstractJwtTokenGenerator - Serializing the principal received
ERROR o.a.c.c.C.[.[.[.[grailsDispatcherServlet] - Servlet.service() for servlet [grailsDispatcherServlet] in context with path [] threw exception
groovy.lang.MissingMethodException: No signature of method: java.lang.String.getUsername() is applicable for argument types: () values: []
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:58)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:64)
at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:52)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGetProperty(AbstractCallSite.java:296)
at grails.plugin.springsecurity.rest.token.generation.jwt.AbstractJwtTokenGenerator.generateClaims(AbstractJwtTokenGenerator.groovy:67)
at grails.plugin.springsecurity.rest.token.generation.jwt.AbstractJwtTokenGenerator$generateClaims$1.callCurrent(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:154)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:182)
at grails.plugin.springsecurity.rest.token.generation.jwt.AbstractJwtTokenGenerator.generateAccessToken(AbstractJwtTokenGenerator.groovy:51)
at grails.plugin.springsecurity.rest.token.generation.jwt.AbstractJwtTokenGenerator$generateAccessToken$0.callCurrent(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:154)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:182)
at grails.plugin.springsecurity.rest.token.generation.jwt.AbstractJwtTokenGenerator.generateAccessToken(AbstractJwtTokenGenerator.groovy:44)
at grails.plugin.springsecurity.rest.token.generation.jwt.AbstractJwtTokenGenerator$generateAccessToken.callCurrent(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:154)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:174)
at grails.plugin.springsecurity.rest.token.generation.jwt.AbstractJwtTokenGenerator.generateAccessToken(AbstractJwtTokenGenerator.groovy:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1426)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSite.invoke(PogoMetaMethodSite.java:169)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.call(PogoMetaMethodSite.java:71)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
at grails.plugin.springsecurity.rest.RestAuthenticationFilter.doFilter(RestAuthenticationFilter.groovy:130)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at grails.plugin.springsecurity.web.authentication.logout.MutableLogoutFilter.doFilter(MutableLogoutFilter.groovy:62)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at grails.plugin.springsecurity.web.SecurityRequestHolderFilter.doFilter(SecurityRequestHolderFilter.groovy:58)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.grails.web.servlet.mvc.GrailsWebRequestFilter.doFilterInternal(GrailsWebRequestFilter.java:75)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.grails.web.filters.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:67)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:103)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
As seen, it does actually think it authenticates shortly before the error. However, then something somewhere trips up, and tries to do a .getUsername() on a String.
I cannot figure out what is trying to do this. I would appreciate any thoughts on what could be causing this issue, or even if I am going about it in a completely wrong way.

Related

Secured controller returns 403 one one action but not on another in Grails app

I have a controller in my app as follows:
#Secured(UserRoles.ROLE_USER)
class ProjectController implements BaseController, SpringSecurityAware {
ProjectService projectService
def create(ProjectCommand command) {
...
}
def update(ProjectCommand command) {
Long projectId = params.id
...
}
}
And it mapped as follows:
post "/v1/api/project" (controller: "project", action: "create")
put "/v1/api/project/$id" {
controller = "project"
action = "update"
constraints {
id(matches:/\\\d+/)
}
}
I am using spring security rest with a custom token storage. The authentication mechanism works properly, as it's been tested and run for a while already.
When I am sending the post request to create the project, everything works fine.
However, if I am trying to update the project I am getting 403 without even getting into the action method.
My request looks like this:
PUT /v1/api/project/12 HTTP/1.1
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ik1qTTFPRGxETjBWR1FUQXlOa00wUkRoR056TkZSRGs1TlRFME1VVXlRa0ZDT0VFelJUazBRdyJ9....0qS2PUw8PQ
Content-Type: application/x-www-form-urlencoded; charset=utf-8
Cookie: JSESSIONID=61F4874A906D706062C0209CEBF2AC3E
Host: localhost:8080
Connection: close
User-Agent: Paw/3.1.7 (Macintosh; OS X/10.13.5) GCDHTTPRequest
Content-Length: 77
title=Project+Update&background=Background&problemStatement=Problem+Statement
Notes:
UserRoles.ROLE_USER is a simple string
If I am debugging the request, the resolved user does have the expected authorities
What am I missing?
I suspect that there is something wrong with UrlMapping
UPDATE
Here is the debug log... It does not make much sense to me. It seems like it authenticated properly, but at the very end, the role was not allowed, even though it was the correct role.
2018-07-03 01:14:59.665 DEBUG --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/v1/api/project/12'; against '/v1/login'
2018-07-03 01:14:59.665 DEBUG --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/v1/api/project/12'; against '/v1/api/**'
2018-07-03 01:14:59.667 DEBUG --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy : /v1/api/project/12 at position 1 of 7 in additional filter chain; firing Filter: 'SecurityRequestHolderFilter'
2018-07-03 01:14:59.674 DEBUG --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy : /v1/api/project/12 at position 2 of 7 in additional filter chain; firing Filter: 'MutableLogoutFilter'
2018-07-03 01:14:59.675 DEBUG --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/v1/api/project/12'; against '/logoff'
2018-07-03 01:14:59.675 DEBUG --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy : /v1/api/project/12 at position 3 of 7 in additional filter chain; firing Filter: 'RestAuthenticationFilter'
2018-07-03 01:14:59.675 DEBUG --- [nio-8080-exec-4] g.p.s.rest.RestAuthenticationFilter : Actual URI is /v1/api/project/12; endpoint URL is /api/login
2018-07-03 01:14:59.675 DEBUG --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy : /v1/api/project/12 at position 4 of 7 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2018-07-03 01:14:59.681 DEBUG --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy : /v1/api/project/12 at position 5 of 7 in additional filter chain; firing Filter: 'RestTokenValidationFilter'
2018-07-03 01:14:59.690 DEBUG --- [nio-8080-exec-4] g.p.s.r.token.bearer.BearerTokenReader : Looking for bearer token in Authorization header, query string or Form-Encoded body parameter
2018-07-03 01:14:59.690 DEBUG --- [nio-8080-exec-4] g.p.s.r.token.bearer.BearerTokenReader : Found bearer token in Authorization header
2018-07-03 01:14:59.690 DEBUG --- [nio-8080-exec-4] g.p.s.r.token.bearer.BearerTokenReader : Token: eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ik1qTTFPRGxETjBWR1FUQXlOa00wUkRoR056TkZSRGs1TlRFME1VVXlRa0ZDT0VFelJUazBRdyJ9.eyJpc3MiOiJodHRwczovL3ByaXotZGV2LmF1dGgwLmNvbS8iLCJzdWIiOiJnb29nbGUtb2F1dGgyfDEwNjY0NzgyMTY3NjY0Mzk5ODE2MCIsImF1ZCI6WyJodHRwczovL3ByaXotZGV2LmF1dGgwLmNvbS9hcGkvdjIvIiwiaHR0cHM6Ly9wcml6LWRldi5hdXRoMC5jb20vdXNlcmluZm8iXSwiaWF0IjoxNTMwNjA1NjU5LCJleHAiOjE1MzA2MTI4NTksImF6cCI6ImtXcnJTT2Nsam1xM3dHTDB1SXR6ZVZ0ZjBMdzdidnlMIiwic2NvcGUiOiJvcGVuaWQgcHJvZmlsZSBlbWFpbCJ9.Oybu4Y4JKhWxuBBWST4f7bqge6AXxvx6wREkhU5OfA8WiR5vJ9Jd8NwjbsdfBss8A4ECjmsDTJb7yCT7nWlr0BAdimhcM6-hU_RtOEl8u_zxPnJrT4I58m_j2eWjoyGCa2snwnBwX1F49ls75bBeH_SEgd4pFanptfUCI2_UluqmvBnSuq_v5bGcB87k0OCcfXR_sZs8Cj_Llt-pgf8yYYisX8EBwfyTm6DeHcSgYPQedGY5zORuZ5T6jlpx3xJwc8J3MrXXUyTRvvZPy7mzyyd12Yfjmh2qrFZ_yFY9yaJVAMtZheLAT0GiamrRtLwL6AcQ-zdJqZJ6ik_4nLPw8g
2018-07-03 01:14:59.699 DEBUG --- [nio-8080-exec-4] g.p.s.rest.RestTokenValidationFilter : Token found: eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ik1qTTFPRGxETjBWR1FUQXlOa00wUkRoR056TkZSRGs1TlRFME1VVXlRa0ZDT0VFelJUazBRdyJ9.eyJpc3MiOiJodHRwczovL3ByaXotZGV2LmF1dGgwLmNvbS8iLCJzdWIiOiJnb29nbGUtb2F1dGgyfDEwNjY0NzgyMTY3NjY0Mzk5ODE2MCIsImF1ZCI6WyJodHRwczovL3ByaXotZGV2LmF1dGgwLmNvbS9hcGkvdjIvIiwiaHR0cHM6Ly9wcml6LWRldi5hdXRoMC5jb20vdXNlcmluZm8iXSwiaWF0IjoxNTMwNjA1NjU5LCJleHAiOjE1MzA2MTI4NTksImF6cCI6ImtXcnJTT2Nsam1xM3dHTDB1SXR6ZVZ0ZjBMdzdidnlMIiwic2NvcGUiOiJvcGVuaWQgcHJvZmlsZSBlbWFpbCJ9.Oybu4Y4JKhWxuBBWST4f7bqge6AXxvx6wREkhU5OfA8WiR5vJ9Jd8NwjbsdfBss8A4ECjmsDTJb7yCT7nWlr0BAdimhcM6-hU_RtOEl8u_zxPnJrT4I58m_j2eWjoyGCa2snwnBwX1F49ls75bBeH_SEgd4pFanptfUCI2_UluqmvBnSuq_v5bGcB87k0OCcfXR_sZs8Cj_Llt-pgf8yYYisX8EBwfyTm6DeHcSgYPQedGY5zORuZ5T6jlpx3xJwc8J3MrXXUyTRvvZPy7mzyyd12Yfjmh2qrFZ_yFY9yaJVAMtZheLAT0GiamrRtLwL6AcQ-zdJqZJ6ik_4nLPw8g
2018-07-03 01:14:59.699 DEBUG --- [nio-8080-exec-4] g.p.s.rest.RestTokenValidationFilter : Trying to authenticate the token
2018-07-03 01:14:59.699 DEBUG --- [nio-8080-exec-4] g.p.s.rest.RestAuthenticationProvider : Use JWT: false
2018-07-03 01:14:59.699 DEBUG --- [nio-8080-exec-4] g.p.s.rest.RestAuthenticationProvider : Trying to validate token eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ik1qTTFPRGxETjBWR1FUQXlOa00wUkRoR056TkZSRGs1TlRFME1VVXlRa0ZDT0VFelJUazBRdyJ9.eyJpc3MiOiJodHRwczovL3ByaXotZGV2LmF1dGgwLmNvbS8iLCJzdWIiOiJnb29nbGUtb2F1dGgyfDEwNjY0NzgyMTY3NjY0Mzk5ODE2MCIsImF1ZCI6WyJodHRwczovL3ByaXotZGV2LmF1dGgwLmNvbS9hcGkvdjIvIiwiaHR0cHM6Ly9wcml6LWRldi5hdXRoMC5jb20vdXNlcmluZm8iXSwiaWF0IjoxNTMwNjA1NjU5LCJleHAiOjE1MzA2MTI4NTksImF6cCI6ImtXcnJTT2Nsam1xM3dHTDB1SXR6ZVZ0ZjBMdzdidnlMIiwic2NvcGUiOiJvcGVuaWQgcHJvZmlsZSBlbWFpbCJ9.Oybu4Y4JKhWxuBBWST4f7bqge6AXxvx6wREkhU5OfA8WiR5vJ9Jd8NwjbsdfBss8A4ECjmsDTJb7yCT7nWlr0BAdimhcM6-hU_RtOEl8u_zxPnJrT4I58m_j2eWjoyGCa2snwnBwX1F49ls75bBeH_SEgd4pFanptfUCI2_UluqmvBnSuq_v5bGcB87k0OCcfXR_sZs8Cj_Llt-pgf8yYYisX8EBwfyTm6DeHcSgYPQedGY5zORuZ5T6jlpx3xJwc8J3MrXXUyTRvvZPy7mzyyd12Yfjmh2qrFZ_yFY9yaJVAMtZheLAT0GiamrRtLwL6AcQ-zdJqZJ6ik_4nLPw8g
2018-07-03 01:14:59.873 DEBUG --- [nio-8080-exec-4] g.p.s.rest.RestAuthenticationProvider : Authentication result: grails.plugin.springsecurity.rest.token.AccessToken(accessToken:eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ik1qTTFPRGxETjBWR1FUQXlOa00wUkRoR056TkZSRGs1TlRFME1VVXlRa0ZDT0VFelJUazBRdyJ9.eyJpc3MiOiJodHRwczovL3ByaXotZGV2LmF1dGgwLmNvbS8iLCJzdWIiOiJnb29nbGUtb2F1dGgyfDEwNjY0NzgyMTY3NjY0Mzk5ODE2MCIsImF1ZCI6WyJodHRwczovL3ByaXotZGV2LmF1dGgwLmNvbS9hcGkvdjIvIiwiaHR0cHM6Ly9wcml6LWRldi5hdXRoMC5jb20vdXNlcmluZm8iXSwiaWF0IjoxNTMwNjA1NjU5LCJleHAiOjE1MzA2MTI4NTksImF6cCI6ImtXcnJTT2Nsam1xM3dHTDB1SXR6ZVZ0ZjBMdzdidnlMIiwic2NvcGUiOiJvcGVuaWQgcHJvZmlsZSBlbWFpbCJ9.Oybu4Y4JKhWxuBBWST4f7bqge6AXxvx6wREkhU5OfA8WiR5vJ9Jd8NwjbsdfBss8A4ECjmsDTJb7yCT7nWlr0BAdimhcM6-hU_RtOEl8u_zxPnJrT4I58m_j2eWjoyGCa2snwnBwX1F49ls75bBeH_SEgd4pFanptfUCI2_UluqmvBnSuq_v5bGcB87k0OCcfXR_sZs8Cj_Llt-pgf8yYYisX8EBwfyTm6DeHcSgYPQedGY5zORuZ5T6jlpx3xJwc8J3MrXXUyTRvvZPy7mzyyd12Yfjmh2qrFZ_yFY9yaJVAMtZheLAT0GiamrRtLwL6AcQ-zdJqZJ6ik_4nLPw8g, accessTokenJwt:null, expiration:null, refreshToken:null, refreshTokenJwt:null, principal:grails.plugin.springsecurity.userdetails.GrailsUser#2dba1e: Username: alex; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER, super:grails.plugin.springsecurity.rest.token.AccessToken#4430b82e: Principal: grails.plugin.springsecurity.userdetails.GrailsUser#2dba1e: Username: alex; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_USER)
2018-07-03 01:14:59.873 DEBUG --- [nio-8080-exec-4] g.p.s.rest.RestTokenValidationFilter : Token authenticated. Storing the authentication result in the security context
2018-07-03 01:14:59.873 DEBUG --- [nio-8080-exec-4] g.p.s.rest.RestTokenValidationFilter : Authentication result: grails.plugin.springsecurity.rest.token.AccessToken(accessToken:eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ik1qTTFPRGxETjBWR1FUQXlOa00wUkRoR056TkZSRGs1TlRFME1VVXlRa0ZDT0VFelJUazBRdyJ9.eyJpc3MiOiJodHRwczovL3ByaXotZGV2LmF1dGgwLmNvbS8iLCJzdWIiOiJnb29nbGUtb2F1dGgyfDEwNjY0NzgyMTY3NjY0Mzk5ODE2MCIsImF1ZCI6WyJodHRwczovL3ByaXotZGV2LmF1dGgwLmNvbS9hcGkvdjIvIiwiaHR0cHM6Ly9wcml6LWRldi5hdXRoMC5jb20vdXNlcmluZm8iXSwiaWF0IjoxNTMwNjA1NjU5LCJleHAiOjE1MzA2MTI4NTksImF6cCI6ImtXcnJTT2Nsam1xM3dHTDB1SXR6ZVZ0ZjBMdzdidnlMIiwic2NvcGUiOiJvcGVuaWQgcHJvZmlsZSBlbWFpbCJ9.Oybu4Y4JKhWxuBBWST4f7bqge6AXxvx6wREkhU5OfA8WiR5vJ9Jd8NwjbsdfBss8A4ECjmsDTJb7yCT7nWlr0BAdimhcM6-hU_RtOEl8u_zxPnJrT4I58m_j2eWjoyGCa2snwnBwX1F49ls75bBeH_SEgd4pFanptfUCI2_UluqmvBnSuq_v5bGcB87k0OCcfXR_sZs8Cj_Llt-pgf8yYYisX8EBwfyTm6DeHcSgYPQedGY5zORuZ5T6jlpx3xJwc8J3MrXXUyTRvvZPy7mzyyd12Yfjmh2qrFZ_yFY9yaJVAMtZheLAT0GiamrRtLwL6AcQ-zdJqZJ6ik_4nLPw8g, accessTokenJwt:null, expiration:null, refreshToken:null, refreshTokenJwt:null, principal:grails.plugin.springsecurity.userdetails.GrailsUser#2dba1e: Username: alex; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER, super:grails.plugin.springsecurity.rest.token.AccessToken#4430b82e: Principal: grails.plugin.springsecurity.userdetails.GrailsUser#2dba1e: Username: alex; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_USER)
2018-07-03 01:14:59.873 DEBUG --- [nio-8080-exec-4] g.p.s.rest.RestTokenValidationFilter : Continuing the filter chain
2018-07-03 01:14:59.878 DEBUG --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy : /v1/api/project/12 at position 6 of 7 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2018-07-03 01:14:59.878 DEBUG --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy : /v1/api/project/12 at position 7 of 7 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2018-07-03 01:14:59.977 DEBUG --- [nio-8080-exec-4] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /v1/api/project/12; Attributes: [_DENY_]
2018-07-03 01:14:59.978 DEBUG --- [nio-8080-exec-4] o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: grails.plugin.springsecurity.rest.token.AccessToken(accessToken:eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ik1qTTFPRGxETjBWR1FUQXlOa00wUkRoR056TkZSRGs1TlRFME1VVXlRa0ZDT0VFelJUazBRdyJ9.eyJpc3MiOiJodHRwczovL3ByaXotZGV2LmF1dGgwLmNvbS8iLCJzdWIiOiJnb29nbGUtb2F1dGgyfDEwNjY0NzgyMTY3NjY0Mzk5ODE2MCIsImF1ZCI6WyJodHRwczovL3ByaXotZGV2LmF1dGgwLmNvbS9hcGkvdjIvIiwiaHR0cHM6Ly9wcml6LWRldi5hdXRoMC5jb20vdXNlcmluZm8iXSwiaWF0IjoxNTMwNjA1NjU5LCJleHAiOjE1MzA2MTI4NTksImF6cCI6ImtXcnJTT2Nsam1xM3dHTDB1SXR6ZVZ0ZjBMdzdidnlMIiwic2NvcGUiOiJvcGVuaWQgcHJvZmlsZSBlbWFpbCJ9.Oybu4Y4JKhWxuBBWST4f7bqge6AXxvx6wREkhU5OfA8WiR5vJ9Jd8NwjbsdfBss8A4ECjmsDTJb7yCT7nWlr0BAdimhcM6-hU_RtOEl8u_zxPnJrT4I58m_j2eWjoyGCa2snwnBwX1F49ls75bBeH_SEgd4pFanptfUCI2_UluqmvBnSuq_v5bGcB87k0OCcfXR_sZs8Cj_Llt-pgf8yYYisX8EBwfyTm6DeHcSgYPQedGY5zORuZ5T6jlpx3xJwc8J3MrXXUyTRvvZPy7mzyyd12Yfjmh2qrFZ_yFY9yaJVAMtZheLAT0GiamrRtLwL6AcQ-zdJqZJ6ik_4nLPw8g, accessTokenJwt:null, expiration:null, refreshToken:null, refreshTokenJwt:null, principal:grails.plugin.springsecurity.userdetails.GrailsUser#2dba1e: Username: alex; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER, super:grails.plugin.springsecurity.rest.token.AccessToken#4430b82e: Principal: grails.plugin.springsecurity.userdetails.GrailsUser#2dba1e: Username: alex; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_USER)
2018-07-03 01:14:59.979 DEBUG --- [nio-8080-exec-4] o.s.s.a.h.RoleHierarchyImpl : getReachableGrantedAuthorities() - From the roles [ROLE_USER] one can reach [ROLE_USER] in zero or more steps.
2018-07-03 01:14:59.997 DEBUG --- [nio-8080-exec-4] o.s.s.w.a.ExceptionTranslationFilter : Access is denied (user is not anonymous); delegating to AccessDeniedHandler
org.springframework.security.access.AccessDeniedException: Access is denied
at org.springframework.security.access.vote.AbstractAccessDecisionManager.checkAllowIfAllAbstainDecisions(AbstractAccessDecisionManager.java:70)
at grails.plugin.springsecurity.access.vote.AuthenticatedVetoableDecisionManager.decide(AuthenticatedVetoableDecisionManager.groovy:50)
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:124)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at javax.servlet.FilterChain$doFilter.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:136)
at grails.plugin.springsecurity.rest.RestTokenValidationFilter.processFilterChain(RestTokenValidationFilter.groovy:121)
at grails.plugin.springsecurity.rest.RestTokenValidationFilter.doFilter(RestTokenValidationFilter.groovy:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at grails.plugin.springsecurity.rest.RestAuthenticationFilter.doFilter(RestAuthenticationFilter.groovy:139)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at grails.plugin.springsecurity.web.authentication.logout.MutableLogoutFilter.doFilter(MutableLogoutFilter.groovy:64)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at grails.plugin.springsecurity.web.SecurityRequestHolderFilter.doFilter(SecurityRequestHolderFilter.groovy:58)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.grails.web.servlet.mvc.GrailsWebRequestFilter.doFilterInternal(GrailsWebRequestFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.grails.web.filters.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:67)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:106)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
2018-07-03 01:15:00.005 DEBUG --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/error'; against '/v1/login'
2018-07-03 01:15:00.005 DEBUG --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/error'; against '/v1/api/**'
2018-07-03 01:15:00.005 DEBUG --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy : /error has no matching filters
Apparently, the problem was not related to security at all.
The issue was with the UrlMapping.
The UrlMapping for the update was supposed to be:
put "/v1/api/project/$id" {
controller = "project"
action = "update"
constraints {
id(matches:/\d+/)
}
}
The regex for constraints was wrong.
However, I still don't understand why 403 was returned and not 404.

Test RestController Delete Crud method return 404 expected 400

I have problem with test method. I want to test delete method ( shouldNotDeletePersonByGivenId) but test doesn't work.
This is My test:
#Test
public void shouldNotDeletePersonByGivenId() throws Exception {
Mockito.doThrow(new PersonService.NoEntityFoundException()).when(personService).deleteById(1L);
mockMvc.perform(delete("/persons/{id}", 1))
.andExpect(status().isBadRequest());
}
In service I have this method:
public static class NoEntityFoundException extends RuntimeException {
public NoEntityFoundException() {
super("There is no Entity in database with given id.");
}
}
When I start test I have request:
java.lang.AssertionError: Status
Expected :400
Actual :404
In restController my delete method look's like this:
#DeleteMapping("/persons/{id}")
public ResponseEntity<?> deleteById(#PathVariable Long id) {
try {
personService.deleteById(id);
return ResponseEntity.ok().body("{Deleted}");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Cant delete! Entity not exist");
}
}
In restController is my path (#PathVariable Long id)
logs:
java.lang.AssertionError: Status
Expected :400
Actual :404
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:55)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:82)
at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:617)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:178)
at com.softwaremind.crew.people.controller.PersonRestControllerTest.shouldNotDeletePersonByGivenId(PersonRestControllerTest.java:90)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
2018-05-07 12:25:02.218 INFO 11348 --- [ Thread-4] o.s.w.c.s.GenericWebApplicationContext : Closing org.springframework.web.context.support.GenericWebApplicationContext#6b6776cb: startup date [Mon May 07 12:24:57 CEST 2018]; root of context hierarchy
2018-05-07 12:25:02.223 INFO 11348 --- [ Thread-4] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2018-05-07 12:25:02.235 WARN 11348 --- [ Thread-4] o.s.b.f.support.DisposableBeanAdapter : Invocation of destroy method failed on bean with name 'inMemoryDatabaseShutdownExecutor': org.h2.jdbc.JdbcSQLException: Baza danych jest już zamknięta (aby zablokować samoczynne zamykanie podczas zamknięcia VM dodaj ";DB_CLOSE_ON_EXIT=FALSE" do URL bazy danych)
Database is already closed (to disable automatic closing at VM shutdown, add ";DB_CLOSE_ON_EXIT=FALSE" to the db URL) [90121-197]
2018-05-07 12:25:02.235 INFO 11348 --- [ Thread-4] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2018-05-07 12:25:02.237 INFO 11348 --- [ Thread-4] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
Check your mockito rule
=> Mockito.doThrow(new PersonService.NoEntityFoundException()).when(personService).deleteById(1L);
And in your code you are calling that function => personService.deleteById(id); => this throws an exception => your catch blocks catches it and =>
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Cant delete! Entity not exist"); => sends NOT_FOUND status which is 404 !!
From above I am expecting that /persons i syour base path . right ?
Can you see the body "Cant delete! Entity not exist" in error logs ?
404 may be coming from wrong path !
Replace HttpStatus.NOT_FOUND with HttpStatus.BAD_REQUEST .....in..........=>
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Cant delete! Entity not exist");

Sending a redirect form a zuul filter

I am implementing an addition to our set of zuul filters.
This additional filter would look at a header and decide that a request should be redirected to a known location that I would configure.
This is the body of the run method for the filter
#Override
public Object run() {
log.debug("Running the PreRouteTransMarkAndLoggingZuulFilter filter ");
// retrieve redirect URL
String redirectURL = filterConfigurationBean.getRedirectURL();
if (redirectURL.isEmpty()) {
return null;
}
// get the white list for allowed entries
Set<String> whiteList = new HashSet<>(Arrays.asList(filterConfigurationBean.getWhiteList().split(",")));
RequestContext ctx = RequestContext.getCurrentContext();
// if request url is part of white list then allow
String url = ctx.getRequest().getRequestURL().toString();
if (checkWhiteList(url, whiteList)) {
return null;
}
// get headers
// check if an authorization header is present
if (validHeader(ctx.getRequest())) {
return null;
}
// if it got to here then if no header then redirect request
try {
ctx.getResponse().sendRedirect(redirectURL);
} catch (IOException e) {
log.error("unable to send a redirect to the login page");
}
return null;
}
Ok, so I implemented and tested it (it is defined as a pre-filter since I don't want the request sent on in the route phase.
Somewhere, a bit further, it tosses an exception.
2017-06-26 17:00:36.482 WARN 6267 --- [tp1303192419-23] o.s.c.n.z.filters.post.SendErrorFilter : Error during filtering
com.netflix.zuul.exception.ZuulException: Filter threw Exception
at com.netflix.zuul.FilterProcessor.processZuulFilter(FilterProcessor.java:227)
at com.netflix.zuul.FilterProcessor.runFilters(FilterProcessor.java:157)
at com.netflix.zuul.FilterProcessor.postRoute(FilterProcessor.java:92)
at com.netflix.zuul.ZuulRunner.postRoute(ZuulRunner.java:87)
at com.netflix.zuul.http.ZuulServlet.postRoute(ZuulServlet.java:107)
at com.netflix.zuul.http.ZuulServlet.service(ZuulServlet.java:88)
at org.springframework.web.servlet.mvc.ServletWrappingController.handleRequestInternal(ServletWrappingController.java:157)
at org.springframework.cloud.netflix.zuul.web.ZuulController.handleRequest(ZuulController.java:44)
at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:50)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:841)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1650)
at org.eclipse.jetty.websocket.server.WebSocketUpgradeFilter.doFilter(WebSocketUpgradeFilter.java:206)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1637)
at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1637)
at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:110)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1637)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:208)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1637)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1637)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1637)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1637)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1637)
at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:106)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1637)
at com.cisco.phisphere.routerservice.BasicCORSFilter.doFilter(BasicCORSFilter.java:78)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1637)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:533)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:190)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:1595)
at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:188)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1253)
at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:168)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:473)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1564)
at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:166)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1155)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
at org.eclipse.jetty.server.Server.handle(Server.java:564)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:317)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:279)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:110)
at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:124)
at org.eclipse.jetty.util.thread.Invocable.invokePreferred(Invocable.java:128)
at org.eclipse.jetty.util.thread.Invocable$InvocableExecutor.invoke(Invocable.java:222)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:294)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.produce(EatWhatYouKill.java:126)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:672)
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:590)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.UndeclaredThrowableException: null
at org.springframework.util.ReflectionUtils.rethrowRuntimeException(ReflectionUtils.java:317)
at org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilter.run(SendResponseFilter.java:115)
at com.netflix.zuul.ZuulFilter.runFilter(ZuulFilter.java:112)
at com.netflix.zuul.FilterProcessor.processZuulFilter(FilterProcessor.java:193)
... 75 common frames omitted
Caused by: org.eclipse.jetty.io.EofException: Closed
at org.eclipse.jetty.server.HttpOutput.write(HttpOutput.java:476)
at org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilter.writeResponse(SendResponseFilter.java:214)
at org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilter.writeResponse(SendResponseFilter.java:183)
at org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilter.run(SendResponseFilter.java:112)
... 77 common frames omitted
So the question I have is this. Is this the right way to perform redirects from zuul?
I have a well defined condition for redirection and a well defined location to send it. I don't want this request to continue if the condition is held but be redirected to an external location.
Thanks
Ok, so I played around and figured it out.
You need to make sure that the RibbonRoutingFilter doesn't trigger by setting ctx.setSendZuulResponse(false) since that filter uses this to figure out if it should fire.
Next set ctx.put(FORWARD_TO_KEY, redirectURL) to make sure that the SendForward filter will fire. Set the redirectURL to where you want it to go.
Also set ctx.getResponse().sendRedirect(redirectURL) or it will tack on the routing path to the original service as a prefix and the redirect will fail.
#Override
public Object run() {
log.debug("Running the AuthorizationPassFilter filter ");
// retrieve redirect URL
String redirectURL = filterConfigurationBean.getRedirectURL();
if (redirectURL.isEmpty()) {
return null;
}
// get the white list for allowed entries
Set<String> whiteList = new HashSet<>(Arrays.asList(filterConfigurationBean.getWhiteList().split(",")));
RequestContext ctx = RequestContext.getCurrentContext();
// if request url is part of white list then allow
String url = ctx.getRequest().getRequestURL().toString();
if (checkWhiteList(url, whiteList)) {
return null;
}
// get headers
// check if an authorization header is present
if (validHeader(ctx.getRequest())) {
return null;
}
// if it got to here then if no header then redirect request
try {
ctx.setSendZuulResponse(false);
ctx.put(FORWARD_TO_KEY, redirectURL);
ctx.setResponseStatusCode(HttpStatus.SC_TEMPORARY_REDIRECT);
ctx.getResponse().sendRedirect(redirectURL);
} catch (IOException e) {
log.error("unable to send a redirect to the login page");
}
return null;
}

How to use OAuth2RestTemplate + Spring 4?

I'm trying to understand how to use a OAuth2RestTemplate object to consume my OAuth2 secured REST service (which is running under a different project and let's assume also on a different server etc...)
f.e. my rest service is:
https://localhost:8443/rest/api/user
-> Accessing this URL generates an error as I am not authenticated
To request a token I would go to:
https://localhost:8443/rest/oauth/token?grant_type=password&client_id=test&client_secret=test&username=USERNAME&password=PASSWORD
After I receive the token I can then connect to the REST API by using the following URL (example token inserted)
https://localhost:8443/rest/api/user?access_token=06
I currently tried something with the following objects:
#EnableOAuth2Client
#Configuration
class MyConfig {
#Value("${oauth.resource:https://localhost:8443}")
private String baseUrl;
#Value("${oauth.authorize:https://localhost:8443/rest/oauth/authorize}")
private String authorizeUrl;
#Value("${oauth.token:https://localhost:8443/rest/oauth/token}")
private String tokenUrl;
#Bean
protected OAuth2ProtectedResourceDetails resource() {
ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
List scopes = new ArrayList<String>(2);
scopes.add("write");
scopes.add("read");
resource.setAccessTokenUri(tokenUrl);
resource.setClientId("test");
resource.setClientSecret("test");
resource.setGrantType("password");
resource.setScope(scopes);
resource.setUsername("test");
resource.setPassword("test");
return resource;
}
#Bean
public OAuth2RestOperations restTemplate() {
CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
AccessTokenRequest atr = new DefaultAccessTokenRequest();
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr));
AuthorizationCodeAccessTokenProvider provider = new AuthorizationCodeAccessTokenProvider();
provider.setRequestFactory(requestFactory);
restTemplate.setAccessTokenProvider(provider);
return restTemplate;
}
}
I am tried to get token in controller like below.
#Controller
public class TestController {
#Autowired
private OAuth2RestOperations restTemplate;
#RequestMapping(value="/", method= RequestMethod.GET)
public String TestForm() {
System.out.println("Token : " + restTemplate.getAccessToken().getValue());
}
}
But i got below exception
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/web] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails cannot be cast to org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails] with root cause
java.lang.ClassCastException: org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails cannot be cast to org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails
at org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider.obtainAccessToken(AuthorizationCodeAccessTokenProvider.java:190)
at org.springframework.security.oauth2.client.OAuth2RestTemplate.acquireAccessToken(OAuth2RestTemplate.java:221)
at org.springframework.security.oauth2.client.OAuth2RestTemplate.getAccessToken(OAuth2RestTemplate.java:173)
at com.divyshivglobalinvestor.web.controller.PersonalLoanController.PersonalLoanForm(PersonalLoanController.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:442)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1082)
at org.apache.coyote.AreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:722)bstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:623)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.Th
From some blog I found that, if we need to grant password then, instead of ResourceOwnerPasswordResourceDetails, it should be used AccessTokenRequest (which is a Map and is ephemeral). It would be great if someone can help me in getting accessToken. :)
Thanks in advance !
You should use ResourceOwnerPasswordAccessTokenProvider instead of AuthorizationCodeAccessTokenProvider in restTemplate bean

NullPointerException from Jboss LdapExtLoginModule

I am attempting to configure Ldap authentication for a Jboss web-app. Jboss loads my module, but does not authenticate credentials that are known to be good. I should point out that my module just extends LdapExtLoginModule without adding any logic. I get the same error when defering directly to LdapExtLoginModule. The error:
PBOX000070: Password invalid/Password required
is returned when I attempt to login. I tracked the error down to a null pointer being thrown by a hashtable.put() operation in org.jboss.security.auth.spi.LdapExtLoginModule.constructInitialLdapContext. Here is the stack trace:
javax.security.auth.login.FailedLoginException: PBOX000070: Password invalid/Password required
at org.jboss.security.auth.spi.UsernamePasswordLoginModule.login(UsernamePasswordLoginModule.java:284)
at com.alstom.auth.login.ldap.CustomLdapLoginModule.login(CustomLdapLoginModule.java:164)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at javax.security.auth.login.LoginContext.invoke(LoginContext.java:762)
at javax.security.auth.login.LoginContext.access$000(LoginContext.java:203)
at javax.security.auth.login.LoginContext$4.run(LoginContext.java:690)
at javax.security.auth.login.LoginContext$4.run(LoginContext.java:688)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.login.LoginContext.invokePriv(LoginContext.java:687)
at javax.security.auth.login.LoginContext.login(LoginContext.java:595)
at org.springframework.security.authentication.jaas.AbstractJaasAuthenticationProvider.authenticate(AbstractJaasAuthenticationProvider.java:149)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
at com.etse.security.SecureMethodAuthenticationManager.authenticate(SecureMethodAuthenticationManager.java:29)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:195)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:149)
at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:169)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:145)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:97)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:102)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:336)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:653)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:920)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
at java.util.Hashtable.put(Hashtable.java:514)
at org.jboss.security.auth.spi.LdapExtLoginModule.constructInitialLdapContext(LdapExtLoginModule.java:742)
at org.jboss.security.auth.spi.LdapExtLoginModule.createLdapInitContext(LdapExtLoginModule.java:463)
at org.jboss.security.auth.spi.LdapExtLoginModule.validatePassword(LdapExtLoginModule.java:340)
at com.alstom.auth.login.ldap.CustomLdapLoginModule.validatePassword(CustomLdapLoginModule.java:152)
at org.jboss.security.auth.spi.UsernamePasswordLoginModule.login(UsernamePasswordLoginModule.java:281)
... 40 more
The function:
private InitialLdapContext constructInitialLdapContext(String dn, Object credential) throws NamingException
{
String protocol = (String)options.get(Context.SECURITY_PROTOCOL);
String providerURL = (String) options.get(Context.PROVIDER_URL);
if (providerURL == null)
providerURL = "ldap://localhost:" + ((protocol != null && protocol.equals("ssl")) ? "636" : "389");
Properties env = constructLdapContextEnvironment(providerURL, dn, credential);
return new InitialLdapContext(env, null);
}
No hashtable.put() operations there so it must come from the InitialLdapContext constructor right?
public InitialLdapContext(Hashtable<?,?> environment,Control[] connCtls) throws NamingException {
super(true); // don't initialize yet
// Clone environment since caller owns it.
Hashtable env = (environment == null)
? new Hashtable(11)
: (Hashtable)environment.clone();
// Put connect controls into environment. Copy them first since
// caller owns the array.
if (connCtls != null) {
Control[] copy = new Control[connCtls.length];
System.arraycopy(connCtls, 0, copy, 0, connCtls.length);
env.put(BIND_CONTROLS_PROPERTY, copy);
}
// set version to LDAPv3
env.put("java.naming.ldap.version", "3");
// Initialize with updated environment
init(env);
}
connCtls is null (see constructor call) so the only put operation is env.put("java.naming.ldap.version", "3") which is obviously fine.
Any idea what's going on here? Thanks.
HashTable does not allow keys to be null. Verify that none of the keys you put into Hashtable env is not null. For example, for
env.put(BIND_CONTROLS_PROPERTY, copy);
BIND_CONTROLS_PROPERTY must not be null.
Hope that helps
IMO, You have a code from another version of the LdapExtLoginModule. The correct one could be this one on GitHub.
The code there is:
private InitialLdapContext constructInitialLdapContext(String dn, Object credential) throws NamingException
{
Properties env = new Properties();
Iterator iter = options.entrySet().iterator();
while (iter.hasNext())
{
Entry entry = (Entry) iter.next();
env.put(entry.getKey(), entry.getValue()); /* this is the line 742 */
}
So there seems to be a login module option with null value. Try to check your configuration.
Please, share more details about your environment next time. It will help a lot to evaluate your problem. The most important details:
application server version
used server configuration (i.e. configuration of the security domain in this case)