我正在编写 JWTLoginFilter 来检查用户并对其进行身份验证,但我无法向数据库发出请求。
这是我的登录过滤器的代码:
import com.fasterxml.jackson.databind.ObjectMapper;
import it.gate42.Model.Credential;
import it.gate42.Model.User;
import it.gate42.repository.User.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(JWTLoginFilter.class);
@Autowired
UserRepository userRepository;
public JWTLoginFilter(String url, AuthenticationManager authManager) {
super(new AntPathRequestMatcher(url));
setAuthenticationManager(authManager);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException, IOException, ServletException {
Credential creds = new ObjectMapper().readValue(req.getInputStream(), Credential.class);
User user = null;
user = userRepository.login(creds);
return new UsernamePasswordAuthenticationToken(
creds.getUsername(),
creds.getPassword()
);
/*return getAuthenticationManager().authenticate(
new UsernamePasswordAuthenticationToken(
creds.getUsername(),
creds.getPassword(),
Collections.emptyList()
)
);*/
}
@Override
protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain, Authentication auth) throws IOException, ServletException {
LOGGER.info("a: " + auth.toString());
TokenAuthenticationService.addAuthentication(res, auth.getName());
}
}
对 userRepository 的任何函数调用我都会收到:
java.lang.NullPointerException: null
at it.gate42.Config.Security.JWTLoginFilter.attemptAuthentication
我如何与我的数据库通信以检查用户?我使用 Spring boot、Jersey、JWT、Mongo 和 Spring security 来过滤路由。
最佳答案
在同一个 JWTLoginFilter 类中,添加以下代码:
@Bean
public UserRepository userRepository() {
return new UserRepository();
}
在同一个类中,删除以下代码:
@Autowired
UserRepository userRepository;
在方法 attemptsAuthentication() 中,更改存储库:
user = userRepository().login(creds);
关于java - Spring引导+Mongo+JWT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43230403/