繁体   English   中英

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

[英]Invalid password is accepted in spring security using custom Authentication Provider

我正在使用基本身份验证与自定义身份验证提供程序一起使用 spring 安全性。

当我尝试通过邮递员调用后端 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
     }
}

邮差

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM