我正在做一个简单的请求,通过 Postman 的ID获取一个用户。但是响应状态是200,它没有返回任何东西。但是在我的用户表中,我有数据。我以为问题出在antMatchers上,但无法管理它。控制台中没有日志数据。我可以访问其他控制器,但这个用户控制器有问题。为什么我无法连接到我的后端?我注意到smth很奇怪。我在授权中使用refreshKey而不是tokenkey,它工作正常。我应该让它保持不变还是需要在授权中使用tokenkey?
Postman
安全配置
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private UserDetailsServiceImpl userDetailsService;
private JwtAuthenticationEntryPoint handler;
public SecurityConfig(UserDetailsServiceImpl userDetailsService, JwtAuthenticationEntryPoint handler) {
this.userDetailsService = userDetailsService;
this.handler = handler;
}
/*@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() {
return new JwtAuthenticationFilter();
}*/
@Bean(BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOriginPattern("*");
config.addAllowedHeader("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
@Override
public void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.cors()
.and()
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(handler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/type")
.permitAll()
.antMatchers(HttpMethod.GET, "/nation")
.permitAll()
.antMatchers(HttpMethod.GET, "/recept")
.permitAll()
.antMatchers(HttpMethod.GET, "/recept/**")
.permitAll()
.antMatchers(HttpMethod.GET, "/ingredient")
.permitAll()
.antMatchers(HttpMethod.GET, "/recept/{\\\\d+}")
.permitAll()
.antMatchers("/users/**")
.permitAll()
.antMatchers("/auth/**")
.permitAll()
.anyRequest().authenticated();
httpSecurity.addFilterBefore(new JwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
用户控制器
@Slf4j
@RestController
public class UserController {
private UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@RequestMapping(value="/users",method= RequestMethod.GET, headers = "Accept=application/json")
public List<UserResponse> getAllUsers(){
return userService.getAllUsers().stream().map(u -> new UserResponse(u)).collect(Collectors.toList());
}
@RequestMapping(value="/users",method= RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<Void> createUser(@RequestBody User newUser) {
User user = userService.saveOneUser(newUser);
if(user != null)
return new ResponseEntity<>(HttpStatus.CREATED);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
@RequestMapping(value="/users/{userId}",method= RequestMethod.GET, headers = "Accept=application/json")
public UserResponse getOneUser(@PathVariable Long userId) {
log.info (String.valueOf (userId));
User user = userService.getOneUserById(userId);
if(user == null) {
throw new UserNotFoundException ();
}
return new UserResponse(user);
}
@RequestMapping(value="/users/{userId}",method= RequestMethod.PUT, headers = "Accept=application/json")
public ResponseEntity<Void> updateOneUser(@PathVariable Long userId, @RequestBody User newUser) {
User user = userService.updateOneUser(userId, newUser);
if(user != null)
return new ResponseEntity<>(HttpStatus.OK);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
@RequestMapping(value="/users/{userId}",method= RequestMethod.DELETE, headers = "Accept=application/json")
public void deleteOneUser(@PathVariable Long userId) {
userService.deleteById(userId);
}
}
使用者回应
@Data
public class UserResponse {
Long id;
int avatarId;
String userName;
public UserResponse(User entity) {
this.id = entity.getId();
this.avatarId = entity.getAvatar();
this.userName = entity.getUser_name ();
}
}
Jwt身份验证入口点
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());
}
}
Jwt身份验证筛选器
public class JwtAuthenticationFilter extends OncePerRequestFilter{
@Autowired
JwtTokenProvider jwtTokenProvider;
@Autowired
UserDetailsServiceImpl userDetailsService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
try {
String jwtToken = extractJwtFromRequest(request);
if(StringUtils.hasText(jwtToken) && jwtTokenProvider.validateToken(jwtToken)) {
Long id = jwtTokenProvider.getUserIdFromJwt(jwtToken);
UserDetails user = userDetailsService.loadUserById(id);
if(user != null) {
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
auth.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(auth);
}
}
} catch(Exception e) {
return;
}
filterChain.doFilter(request, response);
}
private String extractJwtFromRequest(HttpServletRequest request) {
String bearer = request.getHeader("Authorization");
if(StringUtils.hasText(bearer) && bearer.startsWith("Bearer "))
return bearer.substring("Bearer".length() + 1);
return null;
}
}
1条答案
按热度按时间qxsslcnc1#
1/为实现此类内容的自动化测试而实施的任何JUnit 5测试。
2/您使用的postman端口是8081,您是否在应用程序-{env}.properties中检查了两次?
3/您使用的是
JwtAuthenticationFilter
,您是否正确配置了角色和用户以正确验证您自己。4/您是否检查了生成的不记名票据:
5/您没有使用任何Spring Security注解来访问您的控制器,该控制器默认位于受保护的区域内。请查看
@PreAuthorize
和@Secured
注解或替代项。不要忘记在您的Security配置类中使用@EnableWebSecurity
激活它们(即WebSecurityConfig.java
或类似的)。