首页 > 解决方案 > 使用自定义身份验证提供程序在 Spring Security 中接受无效密码

问题描述

我正在使用带有基本身份验证的自定义身份验证提供程序的弹簧安全性。

当我试图通过邮递员进行后端 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
     }
}

邮差

标签: javaspringspring-securityrest

解决方案


发生这种情况是因为 Spring Security 正在创建一个会话,该会话在成功验证后作为 Cookie 返回(您可以在 Postman 响应的 Cookies 面板中检查这一点)。对于进一步的请求,即使您提供了无效的凭据,Postman 也会发送此会话 cookie,该 cookie 将用于身份验证。

要消除这种影响,您可以将会话管理策略更新为SessionCreationPolicy.STATELESS,这将确保应用程序没有创建会话,Basic Auth并且请求中发送的凭据用于身份验证。

您可以像这样更新会话管理策略:

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

推荐阅读