如何仅在安全端点上应用 spring 安全过滤器? [英] How to apply spring security filter only on secured endpoints?
问题描述
我有以下 Spring Security 配置:
I have the following Spring Security configuration:
httpSecurity
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/**").fullyAuthenticated()
.and()
.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
authenticationTokenFilterBean()
甚至适用于与 /api/**
表达式不匹配的端点.我也尝试添加以下配置代码
The authenticationTokenFilterBean()
is applied even on endpoints that do not match /api/**
expression. I also tried adding the following configuration code
@Override
public void configure(WebSecurity webSecurity) {
webSecurity.ignoring().antMatchers("/some_endpoint");
}
但这仍然没有解决我的问题.如何告诉 spring security 仅在与安全 URI 表达式匹配的端点上应用过滤器?谢谢
but this still did not solve my problem. How can I tell spring security to apply filters only on endpoints that match the secured URI expression? Thank you
推荐答案
我有一个具有相同要求的应用程序,为了解决它,我基本上将 Spring Security 限制为给定的 ant 匹配模式(使用 antMatcher
) 如下:
I have an application with the same requirement and to solve it I basically restricted Spring Security to a given ant match patter (using antMatcher
) as follows:
http.antMatcher("/api/**").authorizeRequests() //
.anyRequest().authenticated() //
.and()
.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
你可以这样理解:for http
只在匹配ant模式/api/**
的请求上调用这些配置,授权any request
authenticationTokenFilterBean()
before
UsernamePasswordAuthenticationFilter代码>.对于所有其他请求,此配置无效.
You can read it as follows: for http
only invoke these configurations on requests matching the ant pattern /api/**
authorizing any request
to authenticated
users and
add filter
authenticationTokenFilterBean()
before
UsernamePasswordAuthenticationFilter
. For all others requests this configuration has no effect.
这篇关于如何仅在安全端点上应用 spring 安全过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!