首页 > 解决方案 > 如何为特定的 Rest Controller 禁用 Spring Boot 身份验证控制

问题描述

我在客户端使用 Angular 并在后端使用 Spring Boot 制作了一个 CRUD 应用程序。然后我用 Okta 实现了身份验证,一切正常。问题是我想从我的主页的数据库中检索一些数据,并显示这些信息,即使没有用户通过身份验证,但我一直收到 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);
}

我该如何解决这种情况?

标签: spring-bootsecurityauthenticationoktahttp-status-code-401

解决方案


将配置方法更新为此并尝试

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/stats/**")
        .permitAll()
        .anyRequest()
        .authenticated()
        .and()
        .oauth2Client()
        .and()
        .oauth2Login();
  }

推荐阅读