Spring endpoint missed no errors - spring

I am successful in hitting other endpoints in my project except one. Yes incredulous. Below will be the Javascript, the Controller endpoint, the Spring Security trace that shows authorization, but a breakpoint fails to capture anything. There are no errors. This is the same technique I use successfully elsewhere in the same project. How do I begin to debug why/how to fix?
<div class="col-md-4" style="padding: 0px 0px 3px;">
<form class="form-inline justify-content-center" th:action="#{/search}" method="POST"
enctype="application/x-www-form-urlencoded" th:id="searchForm" th:object="${EDIType}">
#RequestMapping(value={"/search"}, method = RequestMethod.POST)
public RedirectView showReportsSearch(#RequestBody EDIType ediType, HttpServletRequest request, Model model,
RedirectAttributes redirectAttributes){
redirectAttributes.addFlashAttribute("EDIType", ediType);
return new RedirectView("clientViewGUI");
}
2022-12-02 13:45:19.876 DEBUG 15128 --- [nio-8080-exec-6] o.s.s.w.a.i.FilterSecurityInterceptor : Authorization successful
2022-12-02 13:45:19.876 DEBUG 15128 --- [nio-8080-exec-6] o.s.s.w.a.i.FilterSecurityInterceptor : RunAsManager did not change Authentication object
2022-12-02 13:45:19.877 DEBUG 15128 --- [nio-8080-exec-6] o.s.security.web.FilterChainProxy : /search reached end of additional filter chain; proceeding with original chain
2022-12-02 13:45:19.949 DEBUG 15128 --- [nio-8080-exec-6] o.s.s.w.a.ExceptionTranslationFilter : Chain processed normally
2022-12-02 13:45:19.952 DEBUG 15128 --- [nio-8080-exec-6] 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#20b51d04
2022-12-02 13:45:19.954 DEBUG 15128 --- [nio-8080-exec-6] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed

Related

How to handle custom exceptions thrown by a filter in Spring Security

I am new to Spring Security.
I have a piece of code where I check if an Authorization header is passed in a request and I throw an exception if it's missing.
public class TokenAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
private static final String BEARER = "Bearer";
public TokenAuthenticationFilter(RequestMatcher requiresAuthenticationRequestMatcher) {
super(requiresAuthenticationRequestMatcher);
}
#Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException, ServletException {
String username = request.getParameter("username");
String authorization = request.getHeader("AUTHORIZATION");
if (!request.getRequestURI().equals(UniversalConstants.LOGIN_PATH)) {
if (authorization == null || authorization.length() == 0 || !authorization.startsWith(BEARER)) {
throw new InvalidCredentialsException("Missing authentication token"); //<-----------------
}
}
String password = request.getParameter("password");
return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken(username, password));
}
I am targeting to handle all exceptions globally so I'm using #ControllerAdvice.
Note: I know that #ControllerAdvice will not work for exceptions thrown outside of Controllers from this and this, so I have also followed the suggestions in these links.
RestAuthenticationEntryPoint.java
#Component("restAuthenticationEntryPoint")
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
public RestAuthenticationEntryPoint() {
System.out.println("RestAuthenticationEntryPoint");
}
#Autowired
#Qualifier("handlerExceptionResolver")
private HandlerExceptionResolver resolver;
#Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
resolver.resolveException(request, response, null, authException);
}
}
This is how I configure the authenticationEntryPoint:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling().authenticationEntryPoint(new RestAuthenticationEntryPoint()).and().cors().and().csrf().disable().exceptionHandling().defaultAuthenticationEntryPointFor(new RestAuthenticationEntryPoint(), PROTECTED_URLS)
.and().authenticationProvider(customAuthenticationProvider())
.addFilterBefore(tokenAuthenticationFilter(), AnonymousAuthenticationFilter.class).authorizeRequests()
.requestMatchers(PROTECTED_URLS).authenticated().and().formLogin().disable().httpBasic().disable();
}
CustomExceptionHandler.java
#ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler({InvalidCredentialsException.class, AuthenticationException.class})
public ResponseEntity<ErrorResponse> handleUnauthorizedError(InvalidCredentialsException e, WebRequest request) {
String errorMessage = e.getLocalizedMessage();
ErrorResponse errorResponse = new ErrorResponse(errorMessage, null);
return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
}
}
InvalidCredentialsException.java
#ResponseStatus(HttpStatus.UNAUTHORIZED)
public class InvalidCredentialsException extends RuntimeException {
public InvalidCredentialsException(String errorMessage) {
super(errorMessage);
}
}
Upon debugging, I've found that the resolver.resolveException(...) in RestAuthenticationEntryPoint and the handleUnauthorizedError(..) in CustomExceptionHandler never get called.
I wish to handle throw new InvalidCredentialsException("Missing authentication token") in an elegant way and show a decent JSON output in the response.
Any help would be appreciated.
Edit: The stack trace
2021-05-20 17:41:29.985 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/public/**']
2021-05-20 17:41:29.986 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/user/hello'; against '/public/**'
2021-05-20 17:41:29.986 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2021-05-20 17:41:29.986 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/error**']
2021-05-20 17:41:29.986 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/user/hello'; against '/error**'
2021-05-20 17:41:29.986 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2021-05-20 17:41:29.986 DEBUG 24808 --- [nio-8181-exec-3] o.s.security.web.FilterChainProxy : /user/hello?username=user&password=user at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2021-05-20 17:41:29.988 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /user/hello' doesn't match 'DELETE /logout'
2021-05-20 17:41:29.988 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2021-05-20 17:41:29.988 DEBUG 24808 --- [nio-8181-exec-3] o.s.security.web.FilterChainProxy : /user/hello?username=user&password=user at position 6 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2021-05-20 17:41:29.989 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.w.s.HttpSessionRequestCache : saved request doesn't match
2021-05-20 17:41:29.989 DEBUG 24808 --- [nio-8181-exec-3] o.s.security.web.FilterChainProxy : /user/hello?username=user&password=user at position 7 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2021-05-20 17:41:29.989 DEBUG 24808 --- [nio-8181-exec-3] o.s.security.web.FilterChainProxy : /user/hello?username=user&password=user at position 8 of 12 in additional filter chain; firing Filter: 'TokenAuthenticationFilter'
2021-05-20 17:41:29.989 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/public/**']
2021-05-20 17:41:29.989 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/user/hello'; against '/public/**'
2021-05-20 17:41:29.989 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2021-05-20 17:41:29.989 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.w.u.matcher.NegatedRequestMatcher : matches = true
2021-05-20 17:41:38.030 DEBUG 24808 --- [nio-8181-exec-3] 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#7fb6b4e0
2021-05-20 17:41:38.030 DEBUG 24808 --- [nio-8181-exec-3] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2021-05-20 17:41:38.030 DEBUG 24808 --- [nio-8181-exec-3] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
2021-05-20 17:41:38.033 ERROR 24808 --- [nio-8181-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
com.spring.fieldSecurity.Exceptions.InvalidCredentialsException: Missing authentication token
at com.spring.fieldSecurity.Service.TokenAuthenticationFilter.attemptAuthentication(TokenAuthenticationFilter.java:44) ~[classes/:na]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
.
. // more error trace here
.
2021-05-20 17:41:38.034 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/public/**']
2021-05-20 17:41:38.034 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/error'; against '/public/**'
2021-05-20 17:41:38.034 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2021-05-20 17:41:38.034 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/error**']
2021-05-20 17:41:38.034 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/error'; against '/error**'
2021-05-20 17:41:38.034 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : matched
2021-05-20 17:41:38.034 DEBUG 24808 --- [nio-8181-exec-3] o.s.security.web.FilterChainProxy : /error?username=user&password=user has an empty filter list
2021-05-20 17:41:38.034 DEBUG 24808 --- [nio-8181-exec-3] o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for GET "/error?username=user&password=user", parameters={masked}
2021-05-20 17:41:38.035 DEBUG 24808 --- [nio-8181-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
2021-05-20 17:41:38.035 DEBUG 24808 --- [nio-8181-exec-3] o.j.s.OpenEntityManagerInViewInterceptor : Opening JPA EntityManager in OpenEntityManagerInViewInterceptor
2021-05-20 17:41:38.724 DEBUG 24808 --- [nio-8181-exec-3] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Using 'application/json', given [application/json] and supported [application/json, application/*+json, application/json, application/*+json]
2021-05-20 17:41:38.724 DEBUG 24808 --- [nio-8181-exec-3] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Writing [{timestamp=Thu May 20 17:41:38 IST 2021, status=500, error=Internal Server Error, message=, path=/us (truncated)...]
2021-05-20 17:41:38.726 DEBUG 24808 --- [nio-8181-exec-3] o.j.s.OpenEntityManagerInViewInterceptor : Closing JPA EntityManager in OpenEntityManagerInViewInterceptor
2021-05-20 17:41:38.727 DEBUG 24808 --- [nio-8181-exec-3] o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 500
Spring security has a filter which is called the ExceptionTranslationFilter which translates AccessDeniedException and AuthenticationException into responses. This filter catches these thrown exceptions in the spring security filter chain.
So if you want to return a custom exception, you could instead inherit from one of these classes instead of RuntimeException and add a custom message.
I just want to emphasis and it can never be said too many times:
Providing friendly error messages in production applications when it comes to authentication/authorization is in general bad practice from a security standpoint. These types of messages can benefit malicious actors, when trying out things so that they realize what they have done wrong and guide them in their hacking attempts.
Providing friendly messages in test environments may be okey, but make sure that they are disabled in production. In production all failed authentication attempts a recommendation is to return a 401 with no additional information. And in graphical clients, generalized error messages should be displayed for instance "failed to authenticate" with no given specifics.
Also:
Writing custom security as you have done is also in general bad practice. Spring security is battle tested with 100000 of applications running it in production environments. Writing a custom filter to handle token and passwords, is in general not needed. Spring security already has implemented filters to handle security and authentication using standards like BASIC authentication and TOKEN/JWT. If you implement a non standard login, one bug might expose your application to a huge risk.
Username and password authentication in spring
Oauth2 authentication in spring

SAML 2.0 integration with Spring boot application issue

I am trying to integrate a Spring boot based application with and IDp that is using componentSpace lib for SAML.
The Spring application (service provider) working fine with other Idp like Octa. But while integrating with component Space it is facing issues and getting following error.
Differences when I compared the logs with Octa request:
Octa is sending Get request while from component space it is post request.
From Octa I am able to get userid (the login id) but from component space it is comping as anonymousUser.
So my question is can we hit Get request instead of Post. And any reason why it is not setting userId value?
Logs:
2020-12-16 07:00:55.800 TRACE 9144 --- [nio-8443-exec-1] o.s.security.web.FilterChainProxy : No security for POST /saml/sso
2020-12-16 07:00:55.800 TRACE 9144 --- [nio-8443-exec-1] o.s.security.web.FilterChainProxy : Invoking RequestCacheAwareFilter (8/13)
2020-12-16 07:00:55.800 TRACE 9144 --- [nio-8443-exec-1] o.s.s.w.s.HttpSessionRequestCache : No saved request
2020-12-16 07:00:55.800 TRACE 9144 --- [nio-8443-exec-1] o.s.security.web.FilterChainProxy : Invoking SecurityContextHolderAwareRequestFilter (9/13)
2020-12-16 07:00:55.803 TRACE 9144 --- [nio-8443-exec-1] o.s.security.web.FilterChainProxy : Invoking AnonymousAuthenticationFilter (10/13)
2020-12-16 07:00:56.809 TRACE 9144 --- [nio-8443-exec-1] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=10.9.109.194, SessionId=null], Granted Authorities=[ROLE_ANONYMOUS]]
2020-12-16 07:00:56.810 TRACE 9144 --- [nio-8443-exec-1] o.s.security.web.FilterChainProxy : Invoking SessionManagementFilter (11/13)
2020-12-16 07:00:56.810 TRACE 9144 --- [nio-8443-exec-1] o.s.security.web.FilterChainProxy : Invoking ExceptionTranslationFilter (12/13)
2020-12-16 07:00:56.810 TRACE 9144 --- [nio-8443-exec-1] o.s.security.web.FilterChainProxy : Invoking FilterSecurityInterceptor (13/13)
2020-12-16 07:00:56.811 TRACE 9144 --- [nio-8443-exec-1] edFilterInvocationSecurityMetadataSource : Did not match request to Ant [pattern='/saml**', OPTIONS] - [hasAnyRole('ROLE_')] (1/2)
2020-12-16 07:00:57.501 TRACE 9144 --- [nio-8443-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Did not re-authenticate AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=10.9.109.194, SessionId=null], Granted Authorities=[ROLE_ANONYMOUS]] before authorizing
2020-12-16 07:00:57.502 TRACE 9144 --- [nio-8443-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Authorizing filter invocation [POST /saml/sso] with attributes [authenticated]
2020-12-16 07:01:03.577 TRACE 9144 --- [nio-8443-exec-1] o.s.s.w.a.expression.WebExpressionVoter : Voted to deny authorization
2020-12-16 07:01:03.580 TRACE 9144 --- [nio-8443-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Failed to authorize filter invocation [POST /saml/sso] with attributes [authenticated] using AffirmativeBased [DecisionVoters=[org.springframework.security.web.access.expression.WebExpressionVoter#24cfcf19], AllowIfAllAbstainDecisions=false]
2020-12-16 07:01:03.709 TRACE 9144 --- [nio-8443-exec-1] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'delegatingApplicationListener'
2020-12-16 07:01:03.709 TRACE 9144 --- [nio-8443-exec-1] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'liveReloadServerEventListener'
2020-12-16 07:01:03.736 TRACE 9144 --- [nio-8443-exec-1] o.s.s.w.a.ExceptionTranslationFilter : Sending AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=10.9.109.194, SessionId=null], 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.4.1.jar:5.4.1]
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.attemptAuthorization(AbstractSecurityInterceptor.java:238) ~[spring-security-core-5.4.1.jar:5.4.1]
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:208) ~[spring-security-core-5.4.1.jar:5.4.1]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:113) ~[spring-security-web-5.4.1.jar:5.4.1]

Wrong Header of the API versioning of the Post Request does not come to handleNoHandlerFoundException?

I am using Spring Boot v2.1.7 + HATEOAS + Spring Rest + Spring Security. When consumer doesn't pass the correct Custom Header in the request, say passes X-Accept-Version=v5, it gives me below error.
Error:
2020-03-26 15:44:48.201 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : POST "/employee-catalog-api/reference-types", parameters={}
2020-03-26 15:44:48.216 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2020-03-26 15:44:48.217 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] .m.c.d.m.p.s.SAMLUserIdentityServiceImpl : Trying to get UserId from Security Context
2020-03-26 15:44:48.224 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.j.s.OpenEntityManagerInViewInterceptor : Opening JPA EntityManager in OpenEntityManagerInViewInterceptor
2020-03-26 15:44:48.234 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found
2020-03-26 15:44:48.234 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] 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#5c85f23b
2020-03-26 15:44:48.234 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2020-03-26 15:44:48.254 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.j.s.OpenEntityManagerInViewInterceptor : Closing JPA EntityManager in OpenEntityManagerInViewInterceptor
2020-03-26 15:44:48.254 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed 404 NOT_FOUND
2020-03-26 15:44:48.258 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.s.s.w.a.ExceptionTranslationFilter : Chain processed normally
2020-03-26 15:44:48.258 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
Code:
#PostMapping(path = "/employee-types", headers = {X-Accept-Version=v1})
public ResponseEntity<Integer> saveEmployeeType(#Valid #RequestBody EmployeeDto employeeDto) {
.....
......
......
return new ResponseEntity<>(HttpStatus.OK);
}
Why its not coming to handleNoHandlerFoundException of the #ControllerAdvice ?
#Override
protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
...................
return handleExceptionInternal(ex, error, getHeaders(), HttpStatus.BAD_REQUEST, request);
}
I was able to solve this issue by taking a reference from : How to set default value of exported as false in rest resource spring data rest.
By adding below logic, it works greatly.
#Component
public class SpringRestConfiguration extends RepositoryRestConfigurerAdapter {
#Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.setRepositoryDetectionStrategy(RepositoryDetectionStrategy.RepositoryDetectionStrategies.ANNOTATED);
config.setExposeRepositoryMethodsByDefault(false);
}
}

Spring boot rest api not failed in case of invalid Endpoint

I am writing a RESTful web services using spring boot. I am using jwt bearer token for authentication an authorisation.
Below is my RestController
#RestController("api/v1/users")
public class UserController {
#Autowired
UserService userService;
#PostMapping
public User saveUser(#RequestBody User user) {
return userService.saveUser(user);
}
#GetMapping
public List<User> getUsers(#RequestParam(required = false) String pageNumber, String pageSize, String role, String status) {
return userService.findAll(pageNumber, pageSize, role, status);
}
}
When I hit the api with request-url
http://localhost:8080/api/v1/users?pageNumber=0&pageSize=6&role=admin
Its work perfectly
but if I change the url endpoint to some invalid endpoint like
http://localhost:8080/api/v1/hhh?pageNumber=0&pageSize=6&role=admin
It still returning same results as per 1st correct endpoint.
Below are some logs statements from springframework debug logging
Checking match of request : '/api/v1/hhh'; against
'/api/test/secureTest'
2019-12-28 19:16:47.601 DEBUG 5591 --- [nio-8080-exec-5]
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request :
'/api/v1/hhh'; against 'api/authenticate'
2019-12-28 19:16:47.601 DEBUG 5591 --- [nio-8080-exec-5]
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request :
'/api/v1/hhh'; against '/api/v1/users/me'
2019-12-28 19:16:47.601 DEBUG 5591 --- [nio-8080-exec-5]
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request :
'/api/v1/hhh'; against '/api/v1/student'
2019-12-28 19:16:47.601 DEBUG 5591 --- [nio-8080-exec-5]
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request :
'/api/v1/hhh'; against '/api/v1/faculty'
2019-12-28 19:16:47.601 DEBUG 5591 --- [nio-8080-exec-5]
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request :
'/api/v1/hhh'; against '/api/v1/admin'
2019-12-28 19:16:47.601 DEBUG 5591 --- [nio-8080-exec-5]
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request :
'/api/v1/hhh'; against '/api/v1/users'
2019-12-28 19:16:47.601 DEBUG 5591 --- [nio-8080-exec-5]
o.s.s.w.a.i.FilterSecurityInterceptor : Public object -
authentication not attempted
2019-12-28 19:16:47.601 DEBUG 5591 --- [nio-8080-exec-5]
o.s.security.web.FilterChainProxy :
/api/v1/hhh?pageNumber=0&pageSize=6&role=admin reached end of
additional filter chain; proceeding with original chain
2019-12-28 19:16:47.602 TRACE 5591 --- [nio-8080-exec-5]
o.s.web.servlet.DispatcherServlet : GET
"/api/v1/hhh?pageNumber=0&pageSize=6&role=admin", parameters={masked},
headers={masked} in DispatcherServlet 'dispatcherServlet'
2019-12-28 19:16:47.602 TRACE 5591 --- [nio-8080-exec-5]
o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance
of singleton bean 'api/v1/users'
2019-12-28 19:16:47.602 TRACE 5591 --- [nio-8080-exec-5]
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to public
java.util.List
com.asset.app.user.UserController.getUsers(java.lang.String,java.lang.String,java.lang.String,java.lang.String)
2019-12-28 19:16:47.602 TRACE 5591 --- [nio-8080-exec-5]
.w.s.m.m.a.ServletInvocableHandlerMethod : Arguments: [0, 6, admin,
null]
I feel Spring cache the endpoint url and used if in case of no match found
Any Idea how to stop this?
if you read the api documentation for #RestController
You see that the annotation constructor takes in a value that is described as:
The value may indicate a suggestion for a logical component name, to
be turned into a Spring bean in case of an autodetected component.
So it is used to set a name for the Bean that vill be created.
It is not used to set a url-mapping like you have done.
#RestController("api/v1/users")
You need to annotate your class with #RequestMapping and also add mappings to the #PostMapping and #GetMapping.
#RestController
#RequestMapping("/api/v1") // Add request mapping
public class FooBar {
#PostMapping("/users") // Add mapping here
public User bar() {
...
}
#GetMapping("/users") // Add mapping here
public List<User> foo() {
...
}
}

Swagger2 ui not accessbile

I am using Swagger in a Spring boot application,
I somehow can access most of Swagger's endpoints such as /v2/api-docs, /swagger-resources but I can't figure out why /swagger-ui.html is not accessible.
I am using these dependencies:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
here is my Swagger Config class:
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("app.controllers"))
.paths(PathSelectors.any())
.build();
}
}
Here is the interesting part of the log:
2017-12-27 14:12:09.896 DEBUG 10212 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : /springfox/swagger-ui.html at position 12 of 13 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2017-12-27 14:12:09.896 DEBUG 10212 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : /springfox/swagger-ui.html at position 13 of 13 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2017-12-27 14:12:09.897 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/springfox/swagger-ui.html'; against '/'
2017-12-27 14:12:09.897 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/springfox/swagger-ui.html'; against '/v2/api-docs'
2017-12-27 14:12:09.897 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/springfox/swagger-ui.html'; against '/configuration/ui'
2017-12-27 14:12:09.897 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/springfox/swagger-ui.html'; against '/swagger-resources'
2017-12-27 14:12:09.897 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/springfox/swagger-ui.html'; against '/configuration/security'
2017-12-27 14:12:09.897 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/springfox/swagger-ui.html'; against '/swagger-ui.html'
2017-12-27 14:12:09.897 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/springfox/swagger-ui.html'; against '/webjars/**'
2017-12-27 14:12:09.897 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /springfox/swagger-ui.html' doesn't match 'POST /login
2017-12-27 14:12:09.897 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /springfox/swagger-ui.html; Attributes: [authenticated]
2017-12-27 14:12:09.897 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#8f3b828e: Principal: 0001; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_ADMIN, ROLE_USER
2017-12-27 14:12:09.903 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.web.access.expression.WebExpressionVoter#45d0a23, returned: 1
2017-12-27 14:12:09.903 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Authorization successful
2017-12-27 14:12:09.903 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : RunAsManager did not change Authentication object
2017-12-27 14:12:09.903 DEBUG 10212 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : /springfox/swagger-ui.html reached end of additional filter chain; proceeding with original chain
2017-12-27 14:12:09.904 DEBUG 10212 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/springfox/swagger-ui.html]
2017-12-27 14:12:09.906 DEBUG 10212 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /springfox/swagger-ui.html
2017-12-27 14:12:09.919 DEBUG 10212 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported
2017-12-27 14:12:09.920 DEBUG 10212 --- [nio-8080-exec-1] .w.s.m.a.ResponseStatusExceptionResolver : Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported
2017-12-27 14:12:09.920 DEBUG 10212 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported
2017-12-27 14:12:09.920 WARN 10212 --- [nio-8080-exec-1] o.s.web.servlet.PageNotFound : Request method 'GET' not supported
2017-12-27 14:12:09.921 DEBUG 10212 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : SecurityContext 'org.springframework.security.core.context.SecurityContextImpl#8f3b828e: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#8f3b828e: Principal: 0001; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_ADMIN, ROLE_USER' stored to HttpSession: 'org.apache.catalina.session.StandardSessionFacade#3bcccd7c
2017-12-27 14:12:09.921 DEBUG 10212 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2017-12-27 14:12:09.921 DEBUG 10212 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Successfully completed request
2017-12-27 14:12:09.922 DEBUG 10212 --- [nio-8080-exec-1] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'delegatingApplicationListener'
2017-12-27 14:12:09.923 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.a.ExceptionTranslationFilter : Chain processed normally
2017-12-27 14:12:09.923 DEBUG 10212 --- [nio-8080-exec-1] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
2017-12-27 14:12:09.923 DEBUG 10212 --- [nio-8080-exec-1] o.s.b.w.f.OrderedRequestContextFilter : Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade#203209de
2017-12-27 14:12:09.923 DEBUG 10212 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost] : Processing ErrorPage[errorCode=0, location=/error]
2017-12-27 14:12:09.928 DEBUG 10212 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error]
2017-12-27 14:12:09.928 DEBUG 10212 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /error
2017-12-27 14:12:09.930 DEBUG 10212 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public org.springframework.http.ResponseEntity io.xhub.secusid.exception.SecusidErrorHandler.error(javax.servlet.http.HttpServletRequest)]
2017-12-27 14:12:09.930 DEBUG 10212 --- [nio-8080-exec-1] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'secusidErrorHandler'
2017-12-27 14:12:09.930 DEBUG 10212 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/error] is: -1
2017-12-27 14:12:09.943 DEBUG 10212 --- [nio-8080-exec-1] i.x.s.exception.SecusidErrorHandler : Request method 'GET' not supported
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported
Try adding a class like this
#Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
// Make Swagger meta-data available via <baseURL>/v2/api-docs/
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
// Make Swagger UI available via <baseURL>/swagger-ui.html
registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/");
}
}

Resources