使用自定义身份验证提供程序在spring security中接受无效密码

u0sqgete  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(293)

我正在使用Spring Security 和使用基本身份验证的自定义身份验证提供程序。
当我试图通过 Postman 点击后端api get调用时,只有当我更改用户名时,它才能正常工作
这里是问题陈述-每当我修改用户名时,只有自定义验证器提供程序工作。一旦我添加了正确的用户名和密码,它就会工作,但在这之后,当我更改密码(给出错误的密码)时,总是显示200个成功响应。若我正在更改用户名(给出错误的用户名),那个么只会调用自定义验证器提供程序并得到401响应。

java spring代码

@Configuration
@EnableWebSecurity
@ComponentScan("com.authentication.service")
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter{     

    @Autowired
    private AuthService authProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception { http
         .httpBasic().and().logout().clearAuthentication(true).and() .authorizeRequests()
         .antMatchers("/index.html", "/", "/home", "/login", "/assets/**").permitAll()
         .anyRequest().authenticated() .and() .csrf()
         .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); }

}

@Service
public class AuthService implements AuthenticationProvider{

@Override
    public Authentication authenticate(Authentication authentication)
            throws org.springframework.security.core.AuthenticationException {
        String userName = (String) authentication.getPrincipal();
        String userPassword = authentication.getCredentials().toString();

        if(authenticateUser(userName, userPassword)) {
            return new UsernamePasswordAuthenticationToken(userName, userPassword, new ArrayList<>());
        } else {
            return null;
        }
    }

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

    public Boolean authenticateUser(String userName, String userPassword) {
        // Using some third party service
        // return true if user is authenticated else false
     }
}

plicqrtu

plicqrtu1#

之所以发生这种情况,是因为spring security正在创建一个会话,该会话在成功身份验证后作为cookie返回(您可以在 Postman 响应中的cookies面板中进行检查)。对于进一步的请求,即使您提供了无效的凭据, Postman 也会发送此会话cookie,用于身份验证。
要删除此影响,可以将会话管理策略更新为 SessionCreationPolicy.STATELESS ,这将确保应用程序和 Basic Auth 请求中发送的凭据用于身份验证。
您可以按如下方式更新会话管理策略:

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter{     
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}

相关问题