使用Spring Security时后端未返回JWT响应求助
无法获取JWT Token问题
向RestController发送请求后,无法获取JWT token,重写代码也没解决。困惑的是,本以为需要输入默认安全密码,但Basic auth已被禁用。
SecurityFilterChain配置代码
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeHttpRequests( requests -> requests .requestMatchers("/").permitAll() .requestMatchers(HttpMethod.POST, "/api/v1/auth").hasRole("ADMIN") .anyRequest().authenticated() ) .exceptionHandling() .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)); //.addFilterAfter(jwtFilter, UsernamePasswordAuthenticationFilter.class) return http.build(); }
AuthController代码
@RestController @RequiredArgsConstructor @RequestMapping("/api/v1") public class AuthController { private final UserDetailsServiceImpl userDetailsService; private final JwtProvider jwtProvider; private final AuthenticationManager authenticationManager; @PreAuthorize("hasAuthority('ADMIN')") @PostMapping("/auth") public ResponseEntity<?> createAuthToken(@RequestBody AuthRequestDTO authRequestDTO) { try { authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(authRequestDTO.getUsername(), authRequestDTO.getPassword())); } catch (BadCredentialsException e) { return new ResponseEntity<>(new ApiError(HttpStatus.UNAUTHORIZED, "Invalid username or password"), HttpStatus.UNAUTHORIZED); } UserDetails userDetails = userDetailsService.loadUserByUsername(authRequestDTO.getUsername()); String token = jwtProvider.generateToken(userDetails); return ResponseEntity.ok(new AuthResponseDTO(token)); } }
内容的提问来源于stack exchange,提问作者Bohdan
相关产品推荐
相关产品推荐

