溫馨提示×

Linux系統中Swagger如何進行權限控制

小樊
44
2025-08-04 23:32:04
欄目: 智能運維

在Linux系統中,Swagger的權限控制可以通過多種方式實現,以下是一些常見的方法:

1. 使用Spring Security進行權限控制

Spring Security是一個強大的安全框架,可以用于認證和授權。以下是一個基本的步驟:

  • 添加依賴:在pom.xml文件中添加Spring Security和Swagger的依賴。
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
  • 配置Spring Security:創建一個配置類來定義訪問控制規則。
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/swagger-ui.html", "/webjars/**", "/swagger-resources/**", "/v2/api-docs").authenticated()
            .anyRequest().permitAll()
            .and()
            .httpBasic();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
            .username("user")
            .password("password")
            .roles("USER")
            .build();
        return new InMemoryUserDetailsManager(user);
    }
}
  • 配置Swagger:創建一個Swagger配置類,啟用Swagger并配置API文檔掃描路徑。
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.example.demo"))
            .paths(PathSelectors.any())
            .build()
            .securitySchemes(Arrays.asList(securityScheme()))
            .securityContexts(Arrays.asList(securityContext()));
    }

    private SecurityScheme securityScheme() {
        return new BasicAuth("user", "password");
    }

    private SecurityContext securityContext() {
        return SecurityContext.builder()
            .securityReferences(defaultAuth())
            .forPaths(PathSelectors.any())
            .build();
    }

    List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Arrays.asList(new SecurityReference("Basic Auth", authorizationScopes));
    }
}

2. 使用OAuth2進行權限控制

OAuth2是一種開放標準,用于授權訪問受保護的資源。以下是一個基本的步驟:

  • 安裝Swagger:使用npm安裝Swagger。
npm install -g swagger-jsdoc swagger-ui-express
  • 創建Swagger配置文件:在項目中創建一個名為swagger.json的文件,用于定義Swagger規范和配置。
{
  "openapi": "3.0.0",
  "info": {
    "title": "My API",
    "version": "1.0.0"
  },
  "components": {
    "securitySchemes": {
      "Bearer": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "JWT"
      }
    }
  },
  "security": [
    {
      "Bearer": []
    }
  ]
}
  • 在API路由中添加權限控制:使用swagger-jsdoc庫來加載Swagger配置,并使用swagger-ui-express庫來啟動Swagger UI。
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerJsDoc = require('swagger-jsdoc');
const app = express();
const swaggerOptions = {
  swaggerDefinition: {
    openapi: '3.0.0',
    info: {
      title: 'My API',
      version: '1.0.0'
    }
  },
  apis: ['./routes/*.js']
};
const swaggerDocs = swaggerJsDoc(swaggerOptions);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});
  • 實現OAuth2授權服務器:創建一個OAuth2授權服務器,用于頒發訪問令牌。
const passport = require('passport');
const OAuth2Strategy = require('passport-oauth2').Strategy;
passport.use(new OAuth2Strategy({
    authorizationURL: 'https://your-auth-server.com/auth',
    tokenURL: 'https://your-auth-server.com/token',
    clientID: 'your-client-id',
    clientSecret: 'your-client-secret',
    callbackURL: 'http://localhost:3000/auth/callback'
  },
  function(accessToken, refreshToken, profile, cb) {
    // 在這里,你可以查找或創建用戶,并將用戶信息與訪問令牌關聯
    // 然后調用cb(null, user)來完成授權過程
  }
));
module.exports = passport;
  • 在API路由中添加OAuth2保護:使用passport.authenticate()中間件來保護API路由。
const express = require('express');
const passport = require('./auth');
const router = express.Router();
router.get('/protected', passport.authenticate('oauth2', { session: false }), (req, res) => {
  res.json({ message: 'This is a protected route' });
});
module.exports = router;

3. 使用基本認證(Basic Auth)

Swagger UI支持Basic Authentication,可以在swagger-ui配置文件中添加認證信息。

  • 修改swagger-ui配置:在swagger-uiindex.html文件中,添加Authorize認證。
const ui = SwaggerUIBundle({
    url: "https://your-api.com/swagger.json",
    dom_id: '#swagger-ui',
    presets: [
        SwaggerUIBundle.presets.apis,
        SwaggerUIStandalonePreset
    ],
    plugins: [
        SwaggerUIBundle.plugins.DownloadUrl
    ],
    requestInterceptor: function (req) {
        req.headers.Authorization = "Basic " + btoa("your-username:your-password");
        return req;
    }
});
  • 使用Nginx配置Basic Auth:如果Swagger部署在Nginx服務器上,可以直接在Nginx里配置HTTP Basic Auth。
server {
    listen 80;
    server_name your-swagger.domain.com;
    location / {
        auth_basic "Restricted Access";
        auth_basic_user_file /etc/nginx/.htpasswd;
        root /var/www/swagger-ui;
        index index.html;
    }
}

4. 使用訪問控制列表(ACL)

訪問控制列表是一種將權限分配給用戶或用戶組的方法。你可以在后端服務中實現ACL,并根據用戶的權限來決定是否允許他們訪問特定的API端點。然后,你可以在Swagger文檔中使用注釋來表示這些關系。

5. 關閉Swagger UI在生產環境的訪問

如果你只想在開發環境使用Swagger,而不希望在生產環境暴露Swagger,建議禁用Swagger UI。

# 在Spring Boot的application.properties文件中
spring.profiles.active=prod
swagger.enabled=false

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女