首页 > 解决方案 > 使用 Spring Security 进行 REST API 授权

问题描述

我正在尝试使用@PreAuthorize("hasAnyRole('ADMIN')")为此目的保护我的 API,我已经实现了UserDetailsService从数据库中获取数据的方法。如果您尝试访问任何受保护的 API,它会向您显示默认登录表单。

我遵循的代码是这个https://github.com/TechPrimers/spring-security-example

我的项目正在成功运行。但是当我尝试在浏览器中访问我的安全 API 时,它没有显示登录表单。

此外,我希望能够在有和没有授权标头的情况下访问 REST API。

本文档

https://howtodoinjava.com/spring-boot2/security-rest-basic-auth-example/

使用InMemoryAuthentication,它还能够使用浏览器和 Postman 访问 API。同时,我正在从我的数据库中获取数据。如何以这种方式自定义我的实现,以便它可以同时适用于浏览器和 Postman?

标签: javaspring-bootspring-security

解决方案


下面的代码需要一个表单来匹配通配符。antMatcher 中需要开头的斜线

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .csrf().disable()
                    .authorizeRequests()
                    .antMatchers("/**/secured/**")
                    .authenticated()
                    .and()
                    .httpBasic();
        }

推荐阅读