【发布时间】:2022-11-28 08:33:34
【问题描述】:
如果我理解得很好,我有自定义身份验证管理器类,我会在其中检查 api 中的某个人是否传递了正确的凭据,但我想知道为什么在我传递空用户名和密码时它没有抛出异常。
@Component
public class AuthManager implements AuthenticationManager {
private final DetailsService detailsService;
private final Logger logger = LoggerFactory.getLogger(AuthManager.class);
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
logger.info("credentials: " + authentication.getCredentials());
logger.info("principals: " + authentication.getPrincipal());
if (authentication.getCredentials() == null || authentication.getPrincipal() == null) {
throw new BadCredentialsException("Credentials are wrong");
}
UserDetails user = loadUser(authentication);
return new UsernamePasswordAuthenticationToken(user.getUsername(), null, user.getAuthorities());
}
private UserDetails loadUser(Authentication auth) {
return detailsService.loadUserByUsername(auth.getPrincipal().toString());
}
那是过滤器
@Component
public class UsernamePasswordJsonFilter extends UsernamePasswordAuthenticationFilter {
private final ObjectMapper objectMapper;
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public UsernamePasswordJsonFilter(ObjectMapper objectMapper, AuthManager manager,
AuthSuccessHandler success, AuthFailureHandler failure) {
this.objectMapper = objectMapper;
setAuthenticationSuccessHandler(success);
setAuthenticationFailureHandler(failure);
setAuthenticationManager(manager);
setFilterProcessesUrl("/login");
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
try {
LoginDTO authenticationRequest = objectMapper.readValue(request.getInputStream(), LoginDTO.class);
Authentication auth = new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(),
authenticationRequest.getPassword());
logger.info("UsernamePasswordJsonFilter");
return getAuthenticationManager().authenticate(auth);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
如果我传递正确的用户名和密码,它就可以工作,但我只是想知道为什么当凭据为空时它没有抛出异常,而且控制台中也没有抛出异常,以防有人要求它
【问题讨论】:
-
空与
null不同。除此之外,authentication.getCredentials().equals(null)是不正确的,因为它永远不会达到那个点。你可以用==查询,永远不要用.equals()查询,之前会引发NPE -
@LeonardoEmmanueldeAzevedo 我编辑了它,但无论如何我不明白为什么它不抛出异常
-
您正在检查
null并且您传递的值为空。做if (authentication.getCredentials() == null || authentication.getPrincipal().isEmpty())
标签: java spring authentication spring-security