微服务架构中我们通常用Oauth2.0,每次请求都需要在请求头中带上Authorization,同时项目采用Swagger在线接口文档才生成文档,怎么才能将Swagger与Oauth2整合呢?我们通常有两种方法来实现。
环境
- Java8
- Spring Boot 2.3.0.RELEASE
- Spring Cloud Hoxton.SR5
搭建认证服务和资源服务
接下来我们搭建Oauth2.0环境。为了方便测试将认证服务和资源服务服务放到同一项目中,如下图所示
具体代码如下
基本配置
@Configurationpublic class SwaggerWebSecurityConfig extends WebSecurityConfigurerAdapter { public static final String[] IGNORING_URL = new String[]{"/v2/api-docs", //swagger api json "/swagger-resources/configuration/ui",//用来获取支持的动作 "/swagger-resources/**",//用来获取api-docs的URI "/swagger-resources/configuration/security",//安全选项 "/webjars/**", "/swagger-ui.html"}; @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers(IGNORING_URL); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("admin") .password("{noop}123456") .authorities("ROLE_ADMIN"); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); }}
- 通过该配置,我们将用户信息放到内存,创建登录用户admin,密码123456。
注:本案例采用 Oauth2.0密码模式,必须提供AuthenticationManager