首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >基于Spring Boot的基本身份验证的OpenAPI3显示方法

基于Spring Boot的基本身份验证的OpenAPI3显示方法
EN

Stack Overflow用户
提问于 2020-08-05 01:31:27
回答 2查看 926关注 0票数 5

我将此依赖项添加到Spring Boot应用程序中

代码语言:javascript
运行
复制
 <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安全配置类:

代码语言:javascript
运行
复制
@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();
    }
}
EN

回答 2

Stack Overflow用户

发布于 2020-08-11 01:27:40

根据您提供的描述,我将推荐以下内容。

  1. 在端点上添加特定于角色的安全性:

例如:

代码语言:javascript
运行
复制
@Override
protected void configure(HttpSecurity http) throws Exception {
http
      .authorizeRequests()
        .antMatchers("/rest/admin/**").hasAnyRole("ADMIN").and()
      .httpBasic()
        .and()
    .csrf().disable();   
}

  1. 在您的@PreAuthorize

中添加'ROLE_

例如:

代码语言:javascript
运行
复制
@PreAuthorize("hasRole('ROLE_USER')")

代码语言:javascript
运行
复制
@PreAuthorize("hasRole('ROLE_ADMIN')")

然后,它应该会像预期的那样工作。

此外,如果它仍然不能像预期的那样工作,我会建议为每个角色创建两个单独的GroupedOpenApi,并根据超级角色的路径标识符(即您的案例中的ADMIN )分隔apis,并在各自的antMatchers上创建各自的安全配置(例如:.antMatchers("/rest/admin/**").hasAnyRole("ADMIN"))。这应该会起作用,然后就会起作用,因为您正在配置每个角色的路径上的安全性,以及为文档配置单独的GroupedOpenApi。

附言:我会首先尝试第一种方法,只使用第二种方法作为后备。

票数 1
EN

Stack Overflow用户

发布于 2020-08-13 22:27:53

我怀疑这是否可能,因为API文档是在启动时生成的(我认为)。

您可以做的是添加文档,指定哪些应用程序接口调用需要哪些安全凭证,我在https://github.com/springdoc/springdoc-openapi#adding-api-information-and-security-documentation上找到了对此的介绍

因此,如果用户能够看到API页面,那么它可能还会看到它无权访问的端点(例如/admin),但是您可以向其添加文档,说明该端点只能由管理员访问。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63252180

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档