如果用户未通过oauth2身份验证,如何禁用对swagger ui页端点的访问

mcdcgff0  于 2021-09-29  发布在  Java
关注(0)|答案(2)|浏览(451)

我正在尝试禁用对的访问 "/v2/api-docs" 如果用户未通过oauth2(swagger ui页面上的授权按钮)验证,则结束点。
我的spring安全配置如下所示:
@configuration@enableresourceserver公共类resourceserverconfig扩展resourceserverconfigureradapter{

@Override
 public void configure(HttpSecurity http) throws Exception {
     http.authorizeRequests().antMatchers("/", "/api/health", "/api/info").permitAll().antMatchers("/api/v1/**").
             authenticated();
 }

}
在这个类中,我配置了swagger oauth2身份验证

@Configuration
 @EnableAuthorizationServer
 public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
  private static final String USER_INVALID = "User Name or Password is invalid";
 @Autowired
 private AuthenticationManager authenticationManager;

 @Autowired
 DataSource dataSource;

 @Autowired
 @Qualifier("customUserDetailsService")
 private UserDetailsService userDetailsService;

 @Bean
 public PasswordEncoder passwordEncoder() {
     return new BCryptPasswordEncoder();
 }

 @Override
 public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
     security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated").allowFormAuthenticationForClients().passwordEncoder(passwordEncoder());
 }

 @Override
 public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
     clients.jdbc(dataSource);
 }

 @Override
 public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

     endpoints.tokenStore(new JdbcTokenStore(dataSource)).authenticationManager(this.authenticationManager).userDetailsService(userDetailsService)
             .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT).exceptionTranslator(ex -> ResponseEntity.status(
                     HttpStatus.UNAUTHORIZED).body(OAuth2Exception.create(OAuth2Exception.UNAUTHORIZED_CLIENT, USER_INVALID))).;
 }

 @Bean
 public FilterRegistrationBean<CorsFilter> corsFilter() {
     UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
     CorsConfiguration config = new CorsConfiguration();
     config.setAllowCredentials(true);
     config.addAllowedOrigin("*");
     config.addAllowedHeader("*");
     config.addAllowedMethod("*");
     source.registerCorsConfiguration("/**", config);
     FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<CorsFilter>(new CorsFilter(source));
     bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
     return bean;
 }

}
在application.properties中,我添加了以下属性:

host.full.dns.auth.link=http://oauthserver.example.com:8081
app.client.id=test-client
app.client.secret=clientSecret
auth.server.schem=http

如果用户没有使用oauth2进行身份验证,如何禁用对api文档的访问?

v1uwarro

v1uwarro1#

只要把它加到蚂蚁匹配器上就行了

@Override
 public void configure(HttpSecurity http) throws Exception {
     http.authorizeRequests()
         .antMatchers("/", "/api/health", "/api/info")
         .permitAll()
         .antMatchers("/api/v1/**", "/v2/api-docs")
         .authenticated();
 }
g9icjywg

g9icjywg2#

swagger-ui.html调用 /v2/api-docs 用敏感的信息填充页面。所以,我放弃了 doFilterInternal 从…起 OncePerRequestFilter . 如果swagger ui调用文档,则调用将通过。如果用户试图直接调用文档的端点,它将显示错误的请求。
@Component 公共类customfilter扩展onceperrequestfilter{@override protected void dofilterinternal(httpservletrequest httpservletrequest,httpservletresponse httpservletresponse,filterchain filterchain)抛出servletexception,ioexception{string path=httpservletrequest.getrequesturi();string authorization=httpservletrequest.getheader(“referer”);if(“/v2/api docs.equals(path)&&authorization.isempty()){httpservletresponse.senderor(httpstatus.bad_request.value(),“无效区域设置”);返回;}filterchain.dofilter(httpservletrequest,httpservletresponse);}
swagger-ui.html文件现在是静态资源。对于已经在swagger-ui.html上受保护的swagger-ui.html,我更改了以下内容:

<script type="text/javascript">
    $(function () {
      var url = window.location.search.match(/url=([^&]+)/);
      var auth = window.sessionStorage.getItem("Authorization");
      if (url && url.length > 1) {
        url = decodeURIComponent(url[1]);
      } else if (auth) {
        url = "/v2/api-docs";
      }
// some code
      window.swaggerUi.load();
      swaggerUi.api.clientAuthorizations.add("oauth2schema",new SwaggerClient.ApiKeyAuthorization("Authorization",'Bearer '+auth,"header"));

      function log() {
        if ('console' in window) {
          console.log.apply(console, arguments);
        }
      }

相关问题