wmSafe致力于互联网资源
道可道,非恒道,名可名,非恒名

【Java】记一次spring cloud Alibaba微服务getaway和oauth2集成Swagger(knife4j)(二)

本文最后更新于2022-6-30,已经有875 天没有更新,如果文章内容或图片资源失效,请留言反馈,我们会及时处理,谢谢!

前言

承接上一章,我们继续将这三个技术整合

同样在oauth2微服务pom中添加swagger依赖


<!-- Swagger -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.plugin</groupId>
                    <artifactId>spring-plugin-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.plugin</groupId>
            <artifactId>spring-plugin-core</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
        <!-- Swagger 增强knife4j 微服务starter -->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-micro-spring-boot-starter</artifactId>
            <version>2.0.8</version>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>2.0.8</version>
            <scope>compile</scope>
        </dependency>

添加Swagger配置文件


import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.RequestParameterBuilder;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.schema.ScalarType;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ParameterType;
import springfox.documentation.service.RequestParameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.Collections;
import java.util.List;

@Configuration
@EnableOpenApi
public class SwaggerConfig implements WebMvcConfigurer {

    @Value("${swagger.prefix}")
    private String swaggerPrefix;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (isPrefixSet()) {
            registry.addResourceHandler(swaggerPrefix + "/swagger-ui.html*").addResourceLocations("classpath:/META-INF/resources/");
            registry.addResourceHandler(swaggerPrefix + "/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        if (isPrefixSet()) {
            registry.addRedirectViewController(swaggerPrefix + "/v2/api-docs", "/v2/api-docs").setKeepQueryParams(true);
            registry.addRedirectViewController(swaggerPrefix + "/swagger-resources", "/swagger-resources");
            registry.addRedirectViewController(swaggerPrefix + "/swagger-resources/configuration/ui", "/swagger-resources/configuration/ui");
            registry.addRedirectViewController(swaggerPrefix + "/swagger-resources/configuration/security", "/swagger-resources/configuration/security");
            registry.addRedirectViewController("/swagger-ui.html", "/404");
        }
    }

    private boolean isPrefixSet() {
        return swaggerPrefix != null && !"".equals(swaggerPrefix) && !"/".equals(swaggerPrefix);
    }

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
                .select()
                .apis(RequestHandlerSelectors.basePackage("org.springframework.security.oauth2"))
                .paths(PathSelectors.any())
                .build()
                .pathMapping("/oauth")
                .globalRequestParameters(globalRequestParameters())
                .apiInfo(apiInfo());
    }

    private List<RequestParameter> globalRequestParameters() {
        RequestParameterBuilder parameterBuilder = new RequestParameterBuilder().in(ParameterType.HEADER).name("Token").required(false).query(param -> param.model(model -> model.scalarModel(ScalarType.STRING)));
        return Collections.singletonList(parameterBuilder.build());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("oauth微服务接口文档")
                .description("oauth微服务接口管理文档")
                .termsOfServiceUrl("http://127.0.0.1:8002/")
                .version("1.0")
                .build();
    }

}

其中:


@Value("${swagger.prefix}")
    private String swaggerPrefix;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (isPrefixSet()) {
            registry.addResourceHandler(swaggerPrefix + "/swagger-ui.html*").addResourceLocations("classpath:/META-INF/resources/");
            registry.addResourceHandler(swaggerPrefix + "/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        if (isPrefixSet()) {
            registry.addRedirectViewController(swaggerPrefix + "/v2/api-docs", "/v2/api-docs").setKeepQueryParams(true);
            registry.addRedirectViewController(swaggerPrefix + "/swagger-resources", "/swagger-resources");
            registry.addRedirectViewController(swaggerPrefix + "/swagger-resources/configuration/ui", "/swagger-resources/configuration/ui");
            registry.addRedirectViewController(swaggerPrefix + "/swagger-resources/configuration/security", "/swagger-resources/configuration/security");
            registry.addRedirectViewController("/swagger-ui.html", "/404");
        }
    }

@Value("${swagger.prefix}")是nacos中拿的路径信息,这里各位可以写死,nacos中示例:
【Java】记一次spring cloud Alibaba微服务getaway和oauth2集成Swagger(knife4j)(二)
作用是因为getaway中已经配置了oauth2的转发规则,这里就会和默认swagger的接口冲突,所以要在这里配置拦截器如果url中包含这个oauth(getaway中配置的路由规则)的路径信息那么就重新进行重定向到正确的swagger接口用于getaway请求

随后在oauth2配置文件中解决cors和csrf跨域

因为不解决这个跨域问题,那么在getaway中调用oauth2的接口的时候会报错,提示跨域错误


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.time.Duration;
import java.util.Arrays;

@EnableWebSecurity
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

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

    //配置认证管理器,授权模式为 "poassword" 时会用到
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 全局配置:忽略url
        /*web.ignoring()
                .antMatchers("/api/user/test")
                .antMatchers("/bi-gateway/api/user/test");*/
    }

    /**
     * 允许匿名访问所有接口 主要是 oauth 接口
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatchers().antMatchers(HttpMethod.OPTIONS, "/oauth/**")
                .and()
                .authorizeRequests()
                .antMatchers("/**").permitAll()
                .and()
                .httpBasic()
                .and()
                .cors()
                .configurationSource(corsConfigurationSource())
                .and()
                .csrf()
                .disable();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowCredentials(true);
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("*"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setMaxAge(Duration.ofHours(1).toHours());
        source.registerCorsConfiguration("/**",configuration);
        return source;
    }
}

另外也要在拦截器中配置规则解决跨域
【Java】记一次spring cloud Alibaba微服务getaway和oauth2集成Swagger(knife4j)(二)


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class GlobalCorsConfiguration {
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}

自此getaway和oauth2集成Swagger(knife4j)整合到此结束
本源码联系站长获取:qq1845440070

本原创文章未经允许不得转载 | 若要转载请注明出处,否则将承担相应的法律责任!
本文链接: https://blog.wm404.com/2022/06/22/87637fda.html
赞赏排名 赞赏支持

评论

  • captcha
暂无评论,要不来一发?

您的关注就是我们最大的支持

联系我们 关于我们