Spring security filter gets the requested urlpattern



This article mainly talks about how to get the requested handler mapping. best _ matching _ pattern _ attribute in spring security filter.


Spring mvc supports configuring variables in urls, which is relatively easy to meet rest-style api design, but also brings some troubles to authentication, monitoring statistics, etc. That is, it is no longer possible to judge by uri alone, and url pattern must be reformed to judge.

The setting of best _ matching _ pattern _ attribute is in the dispatch servlet of spring mvc, but the filter execution order of spring security is before mvc, so the filter in spring security cannot get best _ matching _ pattern _ attribute.

So in this case, how do you get it yourself


The answer is to start with RequestMappinghandlerMapping and get Handler, that is, call this method Handler Mapping. GetHandler (HTTP Servlet Request) Servlet Request);
It triggers the calculation of best _ matching _ pattern _ attribute in advance, and then it can be taken from ATTRIUTE normally.

Implementation instance

HandlerExecutionChain chain = handlerMapping.getHandler((HttpServletRequest) servletRequest);
String urlPattern = servletRequest.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);

The core logic for calculating best _ matching _ pattern _ attribute is in the method of handlermapping.gethandler (http servlet request) . as for how the source code is, a special article will be written afterwards.

This is the end of the story.