且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Spring Boot 预授权和自定义 AuthenticationFilter

更新时间:2022-05-28 09:37:36

Spring Security 的配置一直很繁琐,唯一的万无一失的方法是:

Spring Security has always been tedious to configure, and the only foolproof ways are:

  • 要么成为这方面的专家并准备好查看来源,然后您就可以手工完成困难的事情
  • 或尽可能多地使用框架提供的内容,并尽可能使用文档中的示例

对于 X509AuthenticationFilter 的配置,HttpSecurity javadoc 给出了方法 x509 和以下示例(适应您的配置 - 请参阅 javadoc 以获取原始一):

For the configuration of an X509AuthenticationFilter, HttpSecurity javadoc gives the method x509 with following example (adapted to your config - see javadoc for original one) :

@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {    

     @Override
     protected void configure(HttpSecurity http) throws Exception {
         http
             .authorizeRequests().anyRequest().permitAll()
             // Example x509() configuration
             .x509();
     }
 }

具有以下指示:方法返回 X509Configurer 以进行进一步的自定义.

with following indication: method returns the X509Configurer for further customizations.

除非你有充分的理由采取不同的做法(如果是这样,请说出来)我强烈建议你坚持这种方法.

Unless you have a good reason to do differently (and if it is the case please say it) I strongly advise you to stick to that method.

但在控制器上使用 pre-post 注释确实是一个坏主意,因为可以直接在 HttpSecurity 配置中完成.它迫使您使用 proxyTargetClass = true.

But it is really a bad idea to use pre-post annotation on a controller, for what could be done directly in HttpSecurity configuration. It forced you to use proxyTargetClass = true.

前后注解通常应用于不需要 proxyTargetClass=true 的服务层方法,因为服务通常通过允许 JDK 代理的接口连接到控制器.

Pre and post annotation are normally applied to methods of service layer what do not require proxyTargetClass=true since services are normally wired to controller through interfaces allowing JDK proxying.