如何从基于 Spring Boot 的 API 返回 JSON 响应而不是 HTML

问题描述 投票:0回答:1

我有一个使用 Spring Boot 版本 2.7.18 创建的简单应用程序,并且也使用 Spring Security。下面是 WebSecurityConfig 类:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.ldapAuthentication()
        .userDnPatterns("uid={0},ou=users")
        .contextSource(contextSource())
        .passwordCompare()
        .passwordAttribute("userPassword");
  }

  @Bean
  public DefaultSpringSecurityContextSource contextSource() {
    return new DefaultSpringSecurityContextSource("ldap://localhost:8389/dc=example,dc=com");
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.cors()
        .configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues())
        .and()
        .csrf()
        .disable()
        .authorizeRequests()
        .antMatchers(HttpMethod.OPTIONS, "/**")
        .permitAll()
        .antMatchers("/actuator/**")
        .permitAll() // Adjust permissions as needed
        .antMatchers("/v1/createUser/**")
        .permitAll() // Exclude /v1/user endpoint from authentication
        .antMatchers("/v1/login/**")
        .permitAll() // Exclude /v1/create endpoint from authentication
        .anyRequest()
        .authenticated()
        .and()
        .formLogin();
  }
}

下面是一个控制器方法:

@RestController
@RequestMapping("/v1")
public class UserController {
@GetMapping(value = "/user", produces = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity<User> getUserByUsername(
      @RequestParam String username,
      @RequestHeader(AuthenticationControllerConstants.AUTHORIZATION_NAME)
          String authorizationToken) {
    if (jwtTokenUtil.validateToken(authorizationToken)) {
      User user = userService.findByUsername(username);
      if (user != null) {
        return ResponseEntity.status(HttpStatus.OK).body(user);
      } else {
        return ResponseEntity.notFound().build();
      }
    } else {
      return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
    }
  }
}

该应用程序正在使用 docker,我使用

docker compose up
命令运行该应用程序。

问题是当我通过 Postman 运行测试时,它总是返回 html 格式的响应。以下是我向 endpont 发送请求时的响应示例 -

http://localhost:8080/v1/user
:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Please sign in</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
    <link href="https://getbootstrap.com/docs/4.0/examples/signin/signin.css" rel="stylesheet"
        crossorigin="anonymous" />
</head>

<body>
    <div class="container">
        <form class="form-signin" method="post" action="/login">
            <h2 class="form-signin-heading">Please sign in</h2>
            <p>
                <label for="username" class="sr-only">Username</label>
                <input type="text" id="username" name="username" class="form-control" placeholder="Username" required autofocus>
            </p>
            <p>
                <label for="password" class="sr-only">Password</label>
                <input type="password" id="password" name="password" class="form-control" placeholder="Password" required>
            </p>
            <input name="_csrf" type="hidden" value="407f9921-a9ee-46b4-bab7-6f50a4fb735f" />
            <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
        </form>
    </div>
</body>

</html>

基本上,我想要 JSON 格式的响应,所以我什至将

produces = MediaType.APPLICATION_JSON_VALUE
添加到控制器方法中,但这并不能解决问题。任何帮助表示赞赏。谢谢!

json spring-boot rest spring-security
1个回答
0
投票

这不是返回类型的问题。您看到的 html 是 Spring 默认返回的内容(不需要任何配置)。这告诉您您没有登录,因此首先使用 html 登录页面登录。如果您想关闭此登录,您

.permitAll

© www.soinside.com 2019 - 2024. All rights reserved.