【发布时间】:2017-08-31 00:31:03
【问题描述】:
我正在编写 JWTLoginFilter 以检查用户并对其进行身份验证,但我无法向 DB 发出请求。
这是我的登录过滤器的代码:
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 不是 Spring bean,这就是依赖注入不起作用的原因。您应该提供弹簧配置。
-
尝试将您的 userRepository 注入 SecurityConfig 类,并将该实例传递给构造函数中的过滤器。
-
谢谢@MaximTulupov
-
@MarcoFerraioli 你在登录里面做什么我被困在同样的情况下我的 mongodb 没有被调用。
标签: java spring mongodb spring-mvc jwt