无法将Spring安全性应用于Java项目
我正在尝试将Prevent Brute Force Authentication Attempts with Spring Security应用到我的Java项目中,我也使用Spring Boot。然而,有一部分使用了web.xml
,但在我的项目中没有web.xml
。那么,有没有可能将这种方法应用到一个没有web.xml
的Spring启动项目中呢
我还试图添加它对maven的依赖,但似乎没有。那么,我该如何应用它呢?或者,对于Java+Spring启动项目,有没有类似的方法可以推荐?我看着贝尔东,但没有。知道吗
更新:另一方面,我实现了除web.xml
之外的所有类,我认为可能没有必要使用web.xml
,因为我已经正常地将登录请求传递给了我的服务
但是,我的服务无法检测失败的登录尝试。我应该从userRepository.findByUsername()
调用某个方法吗?方法找不到用户?知道吗
注:还有一篇关于https://github.com/Baeldung/spring-security-registration/tree/master/src/main/java/com/baeldung/security的文章的GitHub
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {
private final UserService userService;
private final UserRepository userRepository;
private final TokenService tokenService;
private final PasswordEncoder passwordEncoder;
private final LoginAttemptService loginAttemptService;
private final HttpServletRequest request;
@Override
@LogExecution
@Transactional
public UserTokenDTO login(final LoginRequest request)
throws JsonProcessingException, JOSEException {
String ip = getClientIP();
if (loginAttemptService.isBlocked(ip)) {
throw new RuntimeException("blocked");
}
final User user = userRepository.findByUsername(request.getEmail())
.orElseThrow(InvalidCredentialsException::new);
final var userDTO = userService.findByUuid(user.getUuid());
final var tokenDTO = tokenService.generateTokens(userDTO, true);
return new UserTokenDTO(userDTO, tokenDTO);
}
private String getClientIP() {
String xfHeader = request.getHeader("X-Forwarded-For");
if (xfHeader == null){
return request.getRemoteAddr();
}
return xfHeader.split(",")[0];
}
}
# 1 楼答案
不幸的是,我无法发表评论(声誉不够),但在下面的链接中,我解释了为什么您无法捕获
AutenticationFailureListener
,您必须使用自定义AuthenticationFailureHandler(正如Pilpo所说)Spring BadCredentials Event not firing
# 2 楼答案
如果你没有网络。xml,您必须在spring配置包中创建这样的类
如果Spring没有检测到
@Configuration
注释,您也可以添加它