gpt4 book ai didi

java - postman 显示 HTML 而不是 JSON

转载 作者:行者123 更新时间:2023-12-02 09:38:53 25 4
gpt4 key购买 nike

我有一个带有引号的简单 Spring Boot + Spring Security REST 应用程序。只有 3 个端点用于 GET、POST、DELETE。仅定义了主持人和管理员帐户。 GET 休息方法工作正常 - 它显示报价列​​表。问题出在 POST 和 DELETE 方法上。当我尝试在 Postman 中调用它们时,它返回 HTML(SecurityConfig 中定义的日志记录表单)。

QuotationApi.java

@RestController
public class QuotationApi {

private List<Quotation> quotations;

public QuotationApi() {
this.quotations = new ArrayList<>();
quotations.add(new Quotation("Those who dare to fail miserably can achieve greatly.", "John F. Kennedy"));
quotations.add(new Quotation("Get busy living or get busy dying.", "Stephen King"));
}

@GetMapping("/api")
public List<Quotation> getQuotation() {
return quotations;
}

@PostMapping("/api")
public boolean addQuotation(@RequestBody Quotation quotation) {
return quotations.add(quotation);
}

@DeleteMapping("/api")
public void deleteQuotation(@RequestParam int index) {
quotations.remove(index);
}
}

SecurityConfig.java

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

// creating users
@Bean
public UserDetailsService userDetailsService() {

UserDetails moderator = User.withDefaultPasswordEncoder()
.username("user")
.password("user")
.roles("MODERATOR")
.build();

UserDetails admin = User.withDefaultPasswordEncoder()
.username("admin")
.password("admin")
.roles("ADMIN")
.build();

return new InMemoryUserDetailsManager(moderator, admin);
}

@Override
protected void configure(HttpSecurity http) throws Exception {

http.authorizeRequests()
.antMatchers(HttpMethod.GET,"/api").permitAll()
.antMatchers(HttpMethod.POST,"/api").hasRole("MODERATOR")
.antMatchers(HttpMethod.DELETE,"/api").hasRole("ADMIN")
.anyRequest().hasRole("ADMIN")
.and()
.formLogin().permitAll()
.and()
.logout().permitAll()
.and()
.csrf().disable();
}
}

我在 Postman 中有 Basic_auth: enter image description here

在 Andreas 的帮助下编辑(工作代码):

@Override
protected void configure(HttpSecurity http) throws Exception {

http.authorizeRequests()
.antMatchers(HttpMethod.GET,"/api").permitAll()
.antMatchers(HttpMethod.POST,"/api").hasRole("MODERATOR")
.antMatchers(HttpMethod.DELETE,"/api").hasRole("ADMIN")
.anyRequest().hasRole("ADMIN")
.and()
.httpBasic()
.and()
.formLogin().permitAll()
.and()
.logout().permitAll()
.and()
.csrf().disable();
}

最佳答案

当您没有在 Spring 中启用基本身份验证时,Postman 发送基本身份验证 header 并不重要。

因为您只调用了formLogin()要启用基于表单的身份验证,您必须使用表单 POST 登录。

当然,您可以调用httpBasic()也启用基本身份验证。

关于java - postman 显示 HTML 而不是 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57272195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com