【问题标题】:How to whitelist single endpoint in Spring Boot application?如何在 Spring Boot 应用程序中将单个端点列入白名单?
【发布时间】:2019-12-27 22:17:21
【问题描述】:

我是 Spring Boot 新手,正在尝试找出将 终点。我已启用 Spring Security。

我有一个带有端点 Hello 的控制器类,它应该返回“hello” 作为响应,并希望任何人无需身份验证即可访问此端点。

@RestController
@RequestMapping(value = {"/employee"})

public class EmployeeController {

    @Autowired
    EmployeeRepository empRepose;

    @Autowired
    EmployeeService empService;

    @Autowired
    private Utility utility;

    @PreAuthorize("permitAll()")
    @GetMapping(value = "/hello", produces = MediaType.APPLICATION_JSON_VALUE)
    public String home() {
        return "Hello Employee!";
    }
}

Spring 安全配置:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class ApplicationBasicAuth extends WebSecurityConfigurerAdapter {

    @Autowired
    RegisterUser beanRegisteruser;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
       /* httpSecurity.csrf().disable()
                .authorizeRequests().anyRequest().authenticated()
                .and().httpBasic();*/

              /*httpSecurity
                        .httpBasic()
                        .and()
                        .authorizeRequests()
                        .antMatchers(HttpMethod.GET, "/employee/**").permitAll()
                        .and()
                        .csrf().disable();*/

        httpSecurity.csrf().disable();

        httpSecurity.authorizeRequests().anyRequest().permitAll();

    }

我尝试了很多方法来将所有端点甚至 1 个我不需要进行身份验证的端点列入白名单。

请帮我找出我在这里做错了什么。

【问题讨论】:

  • 您的代码应该可以工作。您必须将响应代码、错误消息和/或日志消息添加到您的问题中。您是在浏览器中输入应用程序的 URL 还是使用任何其他客户端?
  • 嗨 Nikolai,我在浏览器和客户端上都试过了,浏览器将我重定向到登录页面,客户端给我 401 错误。

标签: rest spring-boot spring-security


【解决方案1】:

您可以使用configure(WebSecurity web) 和/或configure(HttpSecurity http) 来实现,如果您同时使用它们,请注意您必须将configure(WebSecurity web) 保持在configure(HttpSecurity http) 之上。您可能会看到更多详细信息here


configure(WebSecurity web)

WebSecurityignoring() 方法的一般使用省略 Spring Security 和 Spring Security 的任何功能都将不可用。

@Override
public void configure(WebSecurity web) throws Exception {
    web
        .ignoring()
        .antMatchers("/hello")
}

configure(HttpSecurity http)

您也可以将configure(HttpSecurity http) 方法与.permitAll() 一起使用,如下所示

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
        .authorizeRequests()
        .antMatchers("/hello").permitAll()
        .anyRequest().authenticated();
}

【讨论】:

  • 嗨,Romil,我试过了,但没有用...我们是否需要在其他地方提及 ApplicationBasicAuth 类,还是需要在相关的 application.properties 文件中添加一些配置?
  • @lalitbhadula 您是否尝试过这两种方法?请与项目结构分享您更新的代码。
  • @lalitbhadula,从/hello 中删除@PreAuthorize("permitAll()") 并重试
猜你喜欢
  • 2020-07-26
  • 2011-01-21
  • 1970-01-01
  • 1970-01-01
  • 2015-08-23
  • 1970-01-01
  • 1970-01-01
  • 2020-03-30
  • 2016-09-03
相关资源
最近更新 更多