【发布时间】:2020-11-12 23:36:52
【问题描述】:
401 Unauthorized 在尝试登录时产生,而注册工作正常。
在调试期间,我发现在调用UserController 的方法authenticationManager.authenticate() 的行上给出了响应。我注意到的另一件事是,由于某种原因,我在使用 JPA 存储库而不是 DAO 时没有遇到这个问题。
我正在使用 PostgreSQL
如果UserController,下面是对应方法的代码:
@RequestMapping(path = "/auth", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public AuthResponse authenticate(@RequestBody AuthRequest req){
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(req.getUsername(), req.getPassword()));
String token = jwtService.generateToken(req.getUsername());
return new AuthResponse(token);
}
JwtFilter.doFilterInternal():
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
String authorizationHeader = httpServletRequest.getHeader("Authorization");
String jwtToken = null;
String username = null;
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer")) {
jwtToken = authorizationHeader.substring(7);
username = jwtService.extractUsername(jwtToken);
}
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
if (jwtService.validateToken(jwtToken, userDetails.getUsername())) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities()
);
usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
SecurityConfig.configure():
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().cors().disable()
.authorizeRequests()
.anyRequest().permitAll()
.and().addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().httpBasic();
}
UserService.loadUserByUsername():
@Service
public class UserService implements IUserService, UserDetailsService {
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
User userByName = userDao.getUserByUsername(s);
return new org.springframework.security.core.userdetails.User(userByName.getUsername(), userByName.getPassword(), userByName.getAuthorities());
}
}
DAO 查询:
@Override
public User getUserByUsername(String username) {
return jdbcTemplate.queryForObject("SELECT * FROM user_table WHERE username = ?", new Object[]{username}, User.class);
}
【问题讨论】:
标签: spring spring-boot spring-security