java - 使用自定义身份验证提供程序在 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
}
}
解决方案
发生这种情况是因为 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);
}
}
推荐阅读
- sql-server - 在祖先表中插入数据并从祖先表中检索数据
- python - 使用 BERT 模型进行推理时没有 batch_size
- javascript - setState 回调函数没有被调用?
- python - 为什么我不能在 PyCharm 中导入两个模块?
- excel - VBA 如何只运行 3 个潜艇中的 1 个?
- django - 在 Django manage.py runserver 默认输出中添加用户名和客户端 IP 地址
- android - 使用反射为私有方法编写测试
- java - 合并我的项目后,如何解决 razorpay 中的 com.razorpay.CheckoutActivity Class not found 异常?在合并之前它工作正常
- javascript - 如何为 prettyPhoto 实现自定义标记触发器
- java - 如何使用 URL 调用 python 脚本