【问题标题】:Can not protect endpoint - default authorization form doesn't appear无法保护端点 - 默认授权表单不出现
【发布时间】:2020-08-09 18:20:36
【问题描述】:

我实现了我可以想象的非常基本的安全示例 - 我只想保护我的 rest api 端点,即:

@RestController
@RequestMapping("/api/public")
public class TestController {
    @GetMapping("test1")
    public String getTest()
    {
        return "test 1";
    }
}

为了保护这个端点,我创建了如下配置类:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http
                .authorizeRequests()
                .antMatchers("/api/public/test1").authenticated()
                .and()
                .httpBasic();

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("admin").password(passwordEncoder().encode("admin123")).roles("ADMIN")
                .and()
                .withUser("dan").password(passwordEncoder().encode("dan123")).roles("USER")
                .and()
                .withUser("manager").password(passwordEncoder().encode("manager123")).roles("MANAGER");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}

如果我启动我的应用程序并转到http://localhost:8080/api/public/test1,结果我会看到单词test 1。这意味着我的安全性不起作用,因为我应该使用默认表单来放置凭据。有人可以向我解释我做错了什么吗?

【问题讨论】:

    标签: java spring-security-rest


    【解决方案1】:

    尝试使用mvcMatchers 而不是antMatchers。 (在您的代码中将单词 antMatchers 替换为 mvcMatchers)。这是因为 antMatchers 是一个较旧的选项,如果端点有一个尾随 / 或类似的东西,它有时不会覆盖端点。

    【讨论】:

      猜你喜欢
      • 2021-09-16
      • 2017-08-20
      • 1970-01-01
      • 1970-01-01
      • 2020-11-09
      • 2019-08-19
      • 2017-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多