Custom provider getting execude on every request with Spring 6 Basic Authentication

huangapple go评论63阅读模式
英文:

Custom provider getting execude on every request with Spring 6 Basic Authentication

问题

Here is the translated content:

目前正在升级我的Web应用程序,从Spring Boot 2升级到版本3。由于Spring Boot 3使用Spring 6,我需要更新我的安全配置。在我的更改之后,我注意到我的自定义身份验证提供程序在每个请求上都会被调用,这导致了大量的数据库流量。如果我使用Spring的默认登录表单,就不会发生这种情况,但如果使用基本身份验证就会发生。

这是我的示例安全配置:

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public AuthenticationManager authenticationManager() {
        return new ProviderManager(new CustomAuthenticationProvider());
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((authorize) -> authorize
                        .anyRequest().authenticated()
                )
                .httpBasic();
        return http.build();
    }
}

我的提供程序如下:

public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {

        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        if ("admin".equals(username) && "admin".equals(password)) {
            var user = User.withUsername("admin").password("admin").authorities(new ArrayList<>()).build();
            return new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities());
        } else {
            throw new
                    BadCredentialsException("系统身份验证失败");
        }
    }

    @Override
    public boolean supports(Class<?> auth) {
        return auth.equals(UsernamePasswordAuthenticationToken.class);
    }
}

简而言之的行为:

SecurityConfig 行为
.formLogin() 1次登录 / 1次提供程序调用
.httpBasic() 每个会话1次登录 / 每个请求1次提供程序调用

我该如何恢复到与Spring 5 / Spring Boot 2相同的旧行为呢?

英文:

Currently working on upgrading my web application from Spring Boot 2 to Version 3. As Spring Boot 3 uses Spring 6 I needed to update my security configuration. After my changes I noticed that my custom authentication provider is getting called on every request which leads to heavy database traffic. It's not happening if I use the spring default login form but with basic authentication.

Here is my sample security configuration:

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public AuthenticationManager authenticationManager() {
        return new ProviderManager(new CustomAuthenticationProvider());
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((authorize) -&gt; authorize
                        .anyRequest().authenticated()
                )
                .httpBasic();
        return http.build();
    }
}

My Provider looks like:

public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {

        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        if (&quot;admin&quot;.equals(username) &amp;&amp; &quot;admin&quot;.equals(password)) {
            var user = User.withUsername(&quot;admin&quot;).password(&quot;admin&quot;).authorities(new ArrayList&lt;&gt;()).build();
            return new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities());
        } else {
            throw new
                    BadCredentialsException(&quot;system authentication failed&quot;);
        }
    }

    @Override
    public boolean supports(Class&lt;?&gt; auth) {
        return auth.equals(UsernamePasswordAuthenticationToken.class);
    }
}

Behavior in short:

SecurityConfig Behavior
.formLogin() 1x Login / Provider-Call
.httpBasic() 1x Login per Session / 1x Provider-Call per request

What can I do to get the old behavior back as it was with Spring 5 / Spring Boot 2?

答案1

得分: 0

你可以通过在安全过滤器链中设置会话创建策略来恢复旧的会话行为,示例代码如下:

.httpBasic(withDefaults())
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
...
英文:

for everyone having the same issue, you can restore the old session behavior by setting the session creation policy in your security filter chain:

.httpBasic(withDefaults())
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
...

huangapple
  • 本文由 发表于 2023年5月10日 17:37:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76216917.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定