我有两种通过电话号码和用户名密码对用户进行身份验证的方法,我试图在我的过滤器中同时使用这两种方法,我应该使用 If 和 Else 还是有更好的方法?我已经尝试了下面的代码,尽管它不起作用。
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try {
String jwt = getJwtFromRequest(request);
if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
Long userId = tokenProvider.getUserIdFromJWT(jwt);
UserDetails userDetails = customUserDetailsService.loadUserById(userId);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
} else if (StringUtils.hasText(jwt) && jwtTokenHandler.validateToken(jwt)) {
String phoneNumber = jwtTokenHandler.validatePhone(jwt) ;
UserDetails userDetailsUser = customUserDetailsService.loadUserPhone(phoneNumber);
UsernamePasswordAuthenticationToken authenticationMobile = new UsernamePasswordAuthenticationToken(userDetailsUser, null, userDetailsUser.getAuthorities());
authenticationMobile.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticationMobile);
}
} catch (Exception ex) {
logger.error("Could not set user authentication in security context", ex);
}
filterChain.doFilter(request, response);
}