Я не могу передать свой запрос на уровень контроллера. Я получаю 400 Bad Request
после прохождения через OncePerRequestFilter
.
Это происходит только для запросов POST, он отлично работает для запросов GET
.
Ниже мой код в Filter
class
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Autowired
private TokenProvider tokenProvider;
@Autowired
private UsersRestServices customUserDetailsService;
private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
final String requestTokenHeader = httpServletRequest.getHeader("Authorization");
logger.info("token received---->" + requestTokenHeader);
String username = null;
String jwtToken = null;
// JWT Token is in the form "Bearer token". Remove Bearer word and get
// only the Token
if (requestTokenHeader != null) {
if (requestTokenHeader.startsWith("Bearer ")) {
jwtToken = requestTokenHeader.substring(7);
try {
logger.info("token for decoded--->" + jwtToken);
username = tokenProvider.getUsernameFromToken(jwtToken);
} catch (IllegalArgumentException e) {
httpServletResponse.sendError(403, "Illegal Argument Exception");
} catch (ExpiredJwtException e) {
logger.info("Token Expired");
httpServletResponse.sendError(403, "Token has Expired");
}
} else {
logger.info("Token does not start with Bearer");
httpServletResponse.sendError(403, "Token does not staet wity Bearer received:" + jwtToken);
}
}
// Once we get the token validate it.
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.customUserDetailsService.loadUserByUsername(username);
// if token is valid configure Spring Security to manually set
// authentication
if (tokenProvider.validateToken(jwtToken, userDetails)) {
logger.info("sending token for validation----->");
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
logger.info("Authenticated the user successfully----->");
usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
// After setting the Authentication in the context, we specify
// that the current user is authenticated. So it passes the
// Spring Security Configurations successfully.
logger.info("setting Authentication in security context----->");
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
logger.info("Agter setting Authentication in security context----->");
}
}
HttpServletRequest request = (HttpServletRequest) httpServletRequest;
HttpServletResponse response = (HttpServletResponse) httpServletResponse;
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET");
response.setHeader("Access-Control-Allow-Headers", "Authorization,Content-Type,ClientName");
// For HTTP OPTIONS verb/method reply with ACCEPTED status code -- per CORS handshake
if (request.getMethod().equals("OPTIONS")) {
response.setStatus(HttpServletResponse.SC_ACCEPTED);
return;
}
filterChain.doFilter(request, response);
}
}
Все вышеперечисленные журналы печатаются в консоли, возможность получать данные для запроса GET, проблема только для запросов POST
Ниже логи для приложения
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.0.RELEASE)
2020-08-03 18:52:48.935 INFO 2021 --- [ main] com.qworks.claims.ClaimsApplication : Starting ClaimsApplication on Naveens-MacBook-Air.local with PID 2021 (/Users/naveen/Documents/personal_dev/springboot/claims/target/classes started by naveen in /Users/naveen/Documents/personal_dev/springboot/claims)
2020-08-03 18:52:48.938 INFO 2021 --- [ main] com.qworks.claims.ClaimsApplication : The following profiles are active: dev
2020-08-03 18:52:50.810 INFO 2021 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFERRED mode.
2020-08-03 18:52:50.962 INFO 2021 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 138ms. Found 3 JPA repository interfaces.
2020-08-03 18:52:52.162 INFO 2021 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 9090 (http)
2020-08-03 18:52:52.176 INFO 2021 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-08-03 18:52:52.176 INFO 2021 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.35]
2020-08-03 18:52:52.350 INFO 2021 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-08-03 18:52:52.350 INFO 2021 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3340 ms
2020-08-03 18:52:52.501 WARN 2021 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-08-03 18:52:52.784 INFO 2021 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-08-03 18:52:52.886 INFO 2021 --- [ task-1] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-08-03 18:52:53.037 INFO 2021 --- [ task-1] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.15.Final
2020-08-03 18:52:53.371 INFO 2021 --- [ task-1] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-08-03 18:52:53.662 INFO 2021 --- [ task-1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-08-03 18:52:54.433 INFO 2021 --- [ task-1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-08-03 18:52:54.489 INFO 2021 --- [ task-1] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
2020-08-03 18:52:56.656 INFO 2021 --- [ task-1] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-08-03 18:52:56.671 INFO 2021 --- [ task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-08-03 18:52:57.366 INFO 2021 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: Ant [pattern='/v2/api-docs'], []
2020-08-03 18:52:57.366 INFO 2021 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: Ant [pattern='/configuration/ui'], []
2020-08-03 18:52:57.366 INFO 2021 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: Ant [pattern='/swagger-resources/**'], []
2020-08-03 18:52:57.367 INFO 2021 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: Ant [pattern='/configuration/security'], []
2020-08-03 18:52:57.367 INFO 2021 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: Ant [pattern='/swagger-ui.html'], []
2020-08-03 18:52:57.367 INFO 2021 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: Ant [pattern='/webjars/**'], []
2020-08-03 18:52:57.432 INFO 2021 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@62108cd3, org.springframework.security.web.context.SecurityContextPersistenceFilter@7530090a, org.springframework.security.web.header.HeaderWriterFilter@20820df0, org.springframework.security.web.authentication.logout.LogoutFilter@5817f1ca, com.qworks.claims.security.JwtAuthenticationFilter@217235f5, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@55fb36de, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@320ff86f, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@7cd1ec54, org.springframework.security.web.session.SessionManagementFilter@38d525aa, org.springframework.security.web.access.ExceptionTranslationFilter@42cc5460, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@fcd0e8d]
2020-08-03 18:52:57.474 INFO 2021 --- [ main] pertySourcedRequestMappingHandlerMapping : Mapped URL path [/v2/api-docs] onto method [springfox.documentation.swagger2.web.Swagger2Controller#getDocumentation(String, HttpServletRequest)]
2020-08-03 18:52:57.994 INFO 2021 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 9090 (http) with context path ''
2020-08-03 18:52:57.996 INFO 2021 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
2020-08-03 18:52:58.022 INFO 2021 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
2020-08-03 18:52:58.066 INFO 2021 --- [ main] s.d.s.w.s.ApiListingReferenceScanner : Scanning for api listing references
2020-08-03 18:52:58.305 INFO 2021 --- [ main] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositories…
2020-08-03 18:52:58.689 INFO 2021 --- [ main] DeferredRepositoryInitializationListener : Spring Data repositories initialized!
2020-08-03 18:52:58.706 INFO 2021 --- [ main] com.qworks.claims.ClaimsApplication : Started ClaimsApplication in 10.476 seconds (JVM running for 11.105)
2020-08-03 18:53:04.137 INFO 2021 --- [nio-9090-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-08-03 18:53:04.138 INFO 2021 --- [nio-9090-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-08-03 18:53:04.156 INFO 2021 --- [nio-9090-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 18 ms
2020-08-03 18:53:04.202 INFO 2021 --- [nio-9090-exec-2] c.q.c.security.JwtAuthenticationFilter : token received---->Bearer ey<removed-for-stackoverflow>
2020-08-03 18:53:04.202 INFO 2021 --- [nio-9090-exec-2] c.q.c.security.JwtAuthenticationFilter : token for decoded--->ey<removed-for-stackoverflow>
2020-08-03 18:53:04.866 INFO 2021 --- [nio-9090-exec-2] c.q.c.security.JwtAuthenticationFilter : sending token for validation----->
2020-08-03 18:53:04.867 INFO 2021 --- [nio-9090-exec-2] c.q.c.security.JwtAuthenticationFilter : Authenticated the user successfully----->
2020-08-03 18:53:04.868 INFO 2021 --- [nio-9090-exec-2] c.q.c.security.JwtAuthenticationFilter : setting Authentication in security context----->
2020-08-03 18:53:04.869 INFO 2021 --- [nio-9090-exec-2] c.q.c.security.JwtAuthenticationFilter : Agter setting Authentication in security context----->