我做了一个CRUD应用,客户端使用Angular,后端使用Spring Boot。问题是我想从数据库中为我的主页检索一些数据,并在没有用户认证的情况下显示这些信息,但我一直收到401 Unauthorized http响应。
我在stackoverflow上阅读了一些其他的问题,这些是我在Spring服务器上尝试的所有配置。
public class SecurityConfig extends WebSecurityConfigurerAdapter{
1)
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated().and().oauth2Client().and().oauth2Login()
.and().csrf().ignoringAntMatchers("/stats/**");
http.cors();
}
2)
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/stats/**").permitAll().anyRequest().authenticated().and().oauth2Client().and().oauth2Login();
http.cors();
}
他们不工作。这是我试图为我的GET方法联系的@RestController。
@RestController
@RequestMapping("/stats")
@CrossOrigin("http://localhost:4200")
public class StatsController {
@Autowired
private CompanyManagerService companyManagerService;
@Autowired
private ReservationService reservationService;
@Autowired
private ReviewService reviewService;
@Autowired
private UserService userService;
@GetMapping("/company")
public ResponseEntity getCompanyCount(){
return new ResponseEntity(companyManagerService.getCompanyCount(), HttpStatus.OK);
}
@GetMapping("/field")
public ResponseEntity getFieldCount(){
return new ResponseEntity(companyManagerService.getFieldCount(), HttpStatus.OK);
}
@GetMapping("/reservation")
public ResponseEntity getReservationCount(){
return new ResponseEntity(reservationService.getCount(), HttpStatus.OK);
}
@GetMapping("/review")
public ResponseEntity getReviewCount(){
return new ResponseEntity(reviewService.getCount(), HttpStatus.OK);
}
我怎么才能解决这个问题?
@EnableWebSecurity
和 @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
**/stats/**
或 /context-path/stats/**
您可以使用 配置(WebSecurity web) 这将绕过安全过滤链,您将能够访问 GET APIs
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("**/stats/**");
}
如果您同时使用 configure(WebSecurity web)
和 configure(HttpSecurity http)
方法,确保你已经将 配置(WebSecurity web) 在...之上 configure(HttpSecurity http) 如上所述 此处
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
// Other Configurations...
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("**/stats/**");
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf().disable().cors().disable()
.authorizeRequests()
.antMatchers("**/stats/**").permitAll()
.anyRequest().authenticated()
.and()
.oauth2Client()
.and()
.oauth2Login();
}
// Other Configurations...
}
将配置方法更新为这个,然后尝试
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/stats/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.oauth2Client()
.and()
.oauth2Login();
}