oauth2 token为空拦截_Swagger整合Oauth2

微服务架构中我们通常用Oauth2.0,每次请求都需要在请求头中带上Authorization,同时项目采用Swagger在线接口文档才生成文档,怎么才能将Swagger与Oauth2整合呢?我们通常有两种方法来实现。

环境

  • Java8
  • Spring Boot 2.3.0.RELEASE
  • Spring Cloud Hoxton.SR5

搭建认证服务和资源服务

接下来我们搭建Oauth2.0环境。为了方便测试将认证服务和资源服务服务放到同一项目中,如下图所示

50d0a02c72b5f6d430b4776133f04723.png

具体代码如下

基本配置

@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();    }}
  1. 通过该配置,我们将用户信息放到内存,创建登录用户admin,密码123456。

注:本案例采用 Oauth2.0密码模式,必须提供AuthenticationManager

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值