【问题标题】:Why does Spring Security return an empty response body?为什么 Spring Security 返回一个空的响应体?
【发布时间】:2020-06-15 21:52:06
【问题描述】:

我有以下 Spring Security 配置:

@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());
}

我使用 authenticated() 方法来保护(过滤)路由。但同样,仅在过滤器端点(/user/authenticate)中,返回状态和空白响应正文。 当我不使用这个时,由 sendError() 生成的响应正常返回。

【问题讨论】:

  • 那么当你成功认证后,sendError() 会发回一个空的body?
  • 成功与否。但我在下面的答案中尝试了这个建议,它也很有效。谢谢你的回复。

标签: java rest spring-security


【解决方案1】:

所以实际上我认为你想要的是 getWriter 方法,因为 sendError 不用于成功结果。

尝试以下方法:

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

【讨论】:

  • 谢谢老兄!这也起到了作用。
猜你喜欢
  • 2019-10-31
  • 1970-01-01
  • 1970-01-01
  • 2015-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-30
  • 1970-01-01
相关资源
最近更新 更多