You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 16:23:24