Spring Security HTT基本身份验证不起作用

时间:2020-11-05 13:23:58

标签: java spring spring-security

我有以下简单的Spring Security身份验证:

@Configuration
@EnableWebSecurity
public class UserSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http.csrf().disable();
    }
}

和REST控制器:

@Controller
@RequestMapping("/news")
public class SimpleController {

    @Autowired
    private ScheduleService scheduleService;

    @ResponseBody
    @PostMapping(value = "/update")
    public ResponseEntity<String> update() {
        log.info("Update started");
        scheduleService.update();
        log.info("Update finished");
        return ResponseEntity.ok("Done.");
    }

application.properites for security:

...
spring.security.user.name=user
spring.security.user.password=123

我期望什么:如果客户端不提供(或无效)凭据,则发生未经授权的错误

我得到了:应用程序正在运行,无需任何身份验证,任何人都可以在没有凭据的情况下使用控制器。

我用邮递员测试过。

出什么问题了?

更新:基本身份验证在我的本地计算机上有效,但在远程服务器上无效。

1 个答案:

答案 0 :(得分:0)

我建议您显式配置基本安全性:

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/**")
                .authorizeRequests(t -> t.anyRequest().authenticated())
                .csrf(t -> t.disable())
                .httpBasic(Customizer.withDefaults()));
        }