Java 为什么Spring Security返回一个空的响应体?

Java 为什么Spring Security返回一个空的响应体?,java,rest,spring-security,Java,Rest,Spring Security,我有以下Spring安全配置: @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and().csrf().disable() .authorizeRequests().antMatchers("/user/authenticate") .permitAll().anyRequest().authenticated() .and() .a

我有以下Spring安全配置:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable()
    .authorizeRequests().antMatchers("/user/authenticate")
    .permitAll().anyRequest().authenticated()
    .and()
    .addFilter(new JwtAuthenticationFilter(authenticationManager()))
    .addFilter(new JwtAuthorizationFilter(authenticationManager()))
    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
我做了一个过滤器,它扩展了
UsernamePasswordAuthenticationFilter
来完成我的身份验证端点。有两种方法可以处理此端点的响应:一种是验证成功,另一种是验证失败:

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain, Authentication authentication) throws IOException {
    UserDto user = ((UserDto) authentication.getPrincipal());

    //Here is converted the roles/authorities from the user.
    List<String> roles = user.getAuthorities().stream().map(GrantedAuthority::getAuthority)
            .collect(Collectors.toList());

    byte[] signingKey = Constants.JWT_SECRET.getBytes();

    //Token builder.
    String token = Jwts.builder().signWith(Keys.hmacShaKeyFor(signingKey), SignatureAlgorithm.HS512)
            .setHeaderParam("typ", Constants.TOKEN_TYPE)
            .setIssuer(Constants.TOKEN_ISSUER)
            .setAudience(Constants.TOKEN_AUDIENCE)
            .setSubject(user.getUsername())
            .setExpiration(new Date(System.currentTimeMillis() + 864000000))
            .claim("rol", roles)
            .compact();

    response.setContentType("application/json");
    response.sendError(response.getStatus(), "Bearer " + token);
}

@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException failed) throws IOException, ServletException {
    System.out.println("MESSAGE UNAUTHORIZED : " + failed.getMessage());

    response.sendError(response.SC_UNAUTHORIZED, failed.getMessage());
}
@覆盖
受保护的void successfulAuthentication(HttpServletRequest请求、HttpServletResponse响应、,
FilterChain FilterChain,身份验证)引发IOException{
UserDto user=((UserDto)authentication.getPrincipal());
//此处转换了用户的角色/权限。
列表角色=user.getAuthories().stream().map(GrantedAuthority::getAuthority)
.collect(Collectors.toList());
byte[]signingKey=Constants.JWT_SECRET.getBytes();
//代币制造者。
String token=Jwts.builder().signWith(key.hmacShaKeyFor(signingKey),SignatureAlgorithm.HS512)
.setHeaderParam(“典型”,常量.TOKEN_类型)
.setIssuer(常量.令牌\u ISSUER)
.setAudience(常数.TOKEN_观众)
.setSubject(user.getUsername())
.setExpiration(新日期(System.currentTimeMillis()+864000000))
.索赔(“rol”,角色)
.compact();
setContentType(“应用程序/json”);
response.senderro(response.getStatus(),“Bearer”+令牌);
}
@凌驾
受保护的无效未成功身份验证(HttpServletRequest请求、HttpServletResponse响应、,
AuthenticationException失败)引发IOException、ServletException{
System.out.println(“消息未经授权:+failed.getMessage());
response.sendError(response.SC_未经授权,失败。getMessage());
}
我使用authenticated()方法来保护(过滤)路由。但同样,仅在过滤器端点(/user/authenticate)中,返回状态和空白响应正文。
当我不使用此方法时,由sendError()生成的响应将正常返回。

因此,实际上我认为您需要的是getWriter方法,因为sendError不用于成功的结果

请尝试以下操作:

response.setStatus(HttpServletResponse.SC_OK); // You can use another constant if u like
response.getWritter().print("Bearer " + token);

因此,当您成功进行身份验证时,sendError()会发回一个空的正文?成功与否。但我在下面的答案中尝试了这个建议,效果也不错。谢谢你的回复。谢谢你!这也起了作用。