Spring WebFilter repeated calls

A project uses Spring Gateway, integrates Security for security authentication, defines a JwtAuthenticationTokenWebFilter, and implements WebFilter. The implementation is as follows:

@Data
@Component
public class JwtAuthenticationTokenWebFilter implements WebFilter {...}
@Autowire
JwtAuthenticationTokenWebFilter jwtFilter;
...
seurity.securityContextRepository(NoOpServerSecurityContextRepository.getInstance())
                .addFilterBefore(jwtFilter, SecurityWebFiltersOrder.FORM_LOGIN)

During the test, the calling address is filtered once before routePredicateMapping, and then filtered again. The log looks like this:

Spring WebFilter repeated calls

After following the call stack several times, I found that when the WebFilterChain is executed twice, the fiilterChain is not the same object, and the filterList of the chain is also different, but JWT filters are injected. The first WebFilterList is obviously a standard web security filter, but the second time is mainly filters at several operation and maintenance levels, so I am not sure whether this injection is reasonable, but I do not understand the design of spring thoroughly.

Spring WebFilter repeated calls

Spring WebFilter repeated calls

With this discovery, I tried to make some adjustments and removed the @Component annotation:

@Data
public class JwtAuthenticationTokenWebFilter implements WebFilter {...}

When injecting into security, manually create a filter:

JwtAuthenticationTokenWebFilter jwtFilter = new JwtAuthenticationTokenWebFilter();
seurity.securityContextRepository(NoOpServerSecurityContextRepository.getInstance())
                .addFilterBefore(jwtFilter, SecurityWebFiltersOrder.FORM_LOGIN)

Call it again and find that the filterList of WebFilterChain is only called for security web filtering, and the jwt filter is no longer included in mertrics, and the problem is solved.
Spring WebFilter repeated calls

Guess you like

Origin blog.51cto.com/10705830/2573631