【问题标题】:How to add filter after completely OAuth2 authenticate in Spring Boot Security?如何在 Spring Boot Security 中完全 OAuth2 身份验证后添加过滤器?
【发布时间】:2020-08-26 18:55:18
【问题描述】:

我正在尝试在 SpringBoot 中 OAuth2 登录后做一些事情。


所以我尝试在 OAuth2LoginAuthenticationFilter 之后添加过滤器。

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                    .antMatchers("/login", "/oauth2/**", "/")
                    .permitAll()
                    .anyRequest().authenticated()
                    .and()
                    .oauth2Login()
                    .and()
                .addFilterAfter(new MyFilter(), OAuth2LoginAuthenticationFilter.class)
                .logout();
    }

但是,它被调用了 3 次。像这样



这是我的代码。


Spring 安全配置类

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                    .antMatchers("/login", "/oauth2/**", "/")
                    .permitAll()
                    .anyRequest().authenticated()
                    .and()
                    .oauth2Login()
                    .and()
                .addFilterAfter(new MyFilter(), OAuth2LoginAuthenticationFilter.class)
                .logout();
    }
}

MyFilter 类

public class MyFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("login success.");
        chain.doFilter(request, response);
    }

}

为什么要叫三遍?我该怎么办?

我只想被叫一次或获得任何其他好方法。

【问题讨论】:

    标签: spring oauth spring-security-oauth2


    【解决方案1】:

    出于这个原因,大多数 Spring 身份验证过滤器都扩展了 Springs OncePerRequestFilter 类。如果您只希望过滤器在每个请求中执行一次,您可以考虑使用它。 你的html页面会有forms,javascript,images,所以当你提交请求的时候,实际上有很多资源被访问,Controller,以及静态内容,images,js等等,每个访问的资源都需要单独评估。

    【讨论】:

    • 感谢您的建议。 :) 但是,我必须使用弹簧容器。 :(
    猜你喜欢
    • 2014-09-04
    • 2021-03-19
    • 1970-01-01
    • 2015-01-08
    • 1970-01-01
    • 2022-01-20
    • 2018-11-29
    • 1970-01-01
    • 2018-09-11
    相关资源
    最近更新 更多