我将此依赖项添加到Spring Boot应用程序中
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.4.3</version>
<type>pom.sha512</type>
</dependency>
然后我就可以打开:https://localhost:8443/v3/api-docs
浏览器确实会询问我的凭据,只要我输入正确的用户/密码,它就可以工作,但它会向我显示全局可用的所有方法。我希望只有用户有权的方法,以显示在api文档中。
对于一个特定的方法,使用这个标记来授权我的调用:@PreAuthorize("hasRole('USER') OR hasRole('ADMIN')")
这是我的web安全配置类:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception
{
auth.inMemoryAuthentication()
.passwordEncoder(new BCryptPasswordEncoder())
.withUser("user").password(new BCryptPasswordEncoder().encode("blabl")).roles("USER")
.and()
.withUser("admin").password(new BCryptPasswordEncoder().encode("blabla")).roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
}
发布于 2020-08-11 01:27:40
根据您提供的描述,我将推荐以下内容。
例如:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/rest/admin/**").hasAnyRole("ADMIN").and()
.httpBasic()
.and()
.csrf().disable();
}
@PreAuthorize
中添加'ROLE_
‘
例如:
@PreAuthorize("hasRole('ROLE_USER')")
或
@PreAuthorize("hasRole('ROLE_ADMIN')")
然后,它应该会像预期的那样工作。
此外,如果它仍然不能像预期的那样工作,我会建议为每个角色创建两个单独的GroupedOpenApi
,并根据超级角色的路径标识符(即您的案例中的ADMIN
)分隔apis,并在各自的antMatchers上创建各自的安全配置(例如:.antMatchers("/rest/admin/**").hasAnyRole("ADMIN")
)。这应该会起作用,然后就会起作用,因为您正在配置每个角色的路径上的安全性,以及为文档配置单独的GroupedOpenApi。
附言:我会首先尝试第一种方法,只使用第二种方法作为后备。
发布于 2020-08-13 22:27:53
我怀疑这是否可能,因为API文档是在启动时生成的(我认为)。
您可以做的是添加文档,指定哪些应用程序接口调用需要哪些安全凭证,我在https://github.com/springdoc/springdoc-openapi#adding-api-information-and-security-documentation上找到了对此的介绍
因此,如果用户能够看到API页面,那么它可能还会看到它无权访问的端点(例如/admin),但是您可以向其添加文档,说明该端点只能由管理员访问。
https://stackoverflow.com/questions/63252180
复制相似问题