我正在尝试实现 jwt 登录示例
在为安全类配置配置方法时,我遇到了一些问题
这是控制器的方法
@PostMapping("api/user/login")
public ResponseEntity<?> login(Principal principal)
{
if (principal == null)
{
return ResponseEntity.ok(principal);
}
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) principal;
User user = userService.findByUsername(token.getName());
user.setToken(jwtTokenProvider.generateToken(token));
return new ResponseEntity<>(user, HttpStatus.OK);
}
这里我有http配置版本
@Override
protected void configure(HttpSecurity http)
throws Exception
{
http.cors().and().authorizeRequests().antMatchers("/resources/**", "/error", "/api/user/**")
.permitAll().antMatchers("/api/admin/**").hasRole("ADMIN").anyRequest()
.fullyAuthenticated().and().logout().permitAll()
.logoutRequestMatcher(new AntPathRequestMatcher("/api/user/logout", "POST")).and()
.formLogin().loginPage("/api/user/login/").permitAll().and().httpBasic().and().csrf()
.disable();
http.addFilter(new JwtAuthorizationFilter(authenticationManager(), jwtTokenProvider));
}
显然我已经允许登录 api 作为 permitall,但它仍然适用于过滤器,任何人都可以解释到底发生了什么
过滤代码
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain)
throws IOException,
ServletException
{
Authentication authentication = jwtTokenProvider.getAuthentication(request);
if (authentication != null && jwtTokenProvider.validateToken(request))
{
SecurityContextHolder.getContext().setAuthentication(authentication);
}
chain.doFilter(request, response);
}
根据我的学习,如果我在 http 配置中允许作为 permitall,它不应该进入过滤器代码。如果我错了,请纠正我。