Fix NullPointerException when logging in

pull/383/head
linlinjie 2 years ago
parent cabcdd4e23
commit 9a12c3ae07

@ -26,6 +26,7 @@ import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
@ -65,14 +66,18 @@ public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilte
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
// Get logged in information from the input stream.
Authentication authenticate = null;
try {
LoginUser loginUser = new ObjectMapper().readValue(request.getInputStream(), LoginUser.class);
rememberMe.set(loginUser.getRememberMe());
return authenticationManager.authenticate(
authenticate = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword(), new ArrayList()));
} catch (IOException e) {
logger.error("attemptAuthentication error :{}", e);
return null;
} catch (BadCredentialsException e) {
log.warn("BadCredentialsException:{}", e.getMessage());
} catch (Exception e) {
log.error("attemptauthentication error:", e);
} finally {
return authenticate;
}
}

@ -21,6 +21,7 @@ import cn.hippo4j.auth.mapper.UserMapper;
import cn.hippo4j.auth.model.UserInfo;
import cn.hippo4j.auth.model.biz.user.JwtUser;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
@ -28,11 +29,13 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;
/**
* User details service impl.
*/
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
@Resource
@ -41,6 +44,10 @@ public class UserDetailsServiceImpl implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
UserInfo userInfo = userMapper.selectOne(Wrappers.lambdaQuery(UserInfo.class).eq(UserInfo::getUserName, userName));
if (Objects.isNull(userInfo)) {
log.warn("User {} not found", userName);
throw new UsernameNotFoundException(userName);
}
JwtUser jwtUser = new JwtUser();
jwtUser.setId(userInfo.getId());
jwtUser.setUsername(userName);

Loading…
Cancel
Save