第十一节 资源服务器api-server集成zuul网关

zuul 集成spring security 作为边缘路由访问时的api权限控制策略

  • api-server作为资源服务器。
    在上一节中,security-server中oauth2作为整个微服务的权限控制中心,主要功能对客户端的
    认证和token的发放,与此向对的就是资源服务器,资源服务器依赖于权限服务器。其他客户端想要
    调用资源服务器的接口,就必须通过权限服务器的认证。

zuul的基本介绍已在第六节中有过基本介绍,可参考第六节 服务端负载均衡

关于资源服务器的api-server的配置使用如下:

  1. pom 添加依赖
 <dependency>
            <groupId>com.xzg</groupId>
            <artifactId>online-table-reservation-common</artifactId>
            <version>v1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-netflix-hystrix-stream</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
        </dependency>
  1. 基本配置,启动类@EnableResourceServer标注该服务为资源服务器
@SpringBootApplication
@EnableEurekaClient
@EnableResourceServer
@Configuration
@ComponentScan({"com.xzg.api.service", "com.xzg.common"})
public class ApiApp {

    private static final Logger LOG = LoggerFactory.getLogger(ApiApp.class);
    static {
        // 本地测试
        LOG.warn("禁用ssl主机名检查,开发截断使用");
        HttpsURLConnection.setDefaultHostnameVerifier((hostname, sslSession) -> true);
    }
    @LoadBalanced
    @Bean
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

    public static void main(String[] args) {
        LOG.info("Register MDCHystrixConcurrencyStrategy");
        HystrixPlugins.getInstance().registerConcurrencyStrategy(new MDCHystrixConcurrencyStrategy());
        SpringApplication.run(ApiApp.class, args);
    }
}
  1. 配置文件中添加权限认证服务配置
#其他略
security:
  oauth2:
    resource:
      userInfoUri: https://localhost:9001/user
management:
  security:
    enabled: false

具体配置可参考源码

  • 如何访问资源服务器中的API
如果资源服务器和授权服务器在同一个应用程序中,并且使用DefaultTokenServices,那么不必太考虑这一点,因为它实现所有必要的接口,因此它是自动一致的。如果资源服务器是一个单独的应用程序(比如本工程),那么必须确保匹配授权服务器的功能,并提供知道如何正确解码令牌的ResourceServerTokenServices。与授权服务器一样,可以经常使用DefaultTokenServices,并且选项大多通过TokenStore(后端存储或本地编码)表示

以下基于security-server模块

  • 源码用户密码以及客户端client_id、client_secret。均为硬编码所以测试时,需要根据自身调整

按照上一节的步骤先获取token(授权码模式):

  1. 发送url获取code
https://localhost:9001/oauth/authorize?response_type=code&client_id=client&redirect_uri=http://localhost:7771/1&scope=apiAccess&state=553344
  1. 认证后取得code换取token
curl -X POST -k -H 'Content-Type: application/x-www-form-urlencoded' -i https://localhost:9001/oauth/token --data 'grant_type=authorization_codet&redirect_uri=http://localhost:7771/1&code=ar2lEB'
图片.png
  1. 获取token后使用token,就可以在请求资源的请求头添加Bearer token
curl -X GET -H 'Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ' -i http://localhost:7771/service

4 执行成功返回结果,Oauth2的基本也就实现了

也可以使用隐式许可方式直接获取token(隐式许可模式),方法如下
直接发送:如果未登陆会转向登陆

请求:
https://localhost:9001/oauth/authorize?response_type=token&client_id=client&redirect_uri=http://localhost:7771&scope=apiAccess&state=553344
返回:
http://localhost:7771/#access_token=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2luZm8iOnsidXNlck5hbWUiOiJjbGllbnQiLCJwYXNzd29yOsTSQRjpKp2pE4ru2elm3uqFY_mduVtvwc92ZSPTNtTtBbijfNU86r7giIxsqaqaliu4pnvyXO2CWP7q74lOGWWDWDtI02u-a6jhpqauM-TjGHAMAxr-VUbyduw&token_type=bearer&state=553344&expires_in=7199&user_info=com.xzg.security.service.securityEtity.BaseUser@3e219620&jti=1521428f-5d94-4a72-befb-57531dab784a

还有一种是直接使用用户密码模式(资源所有者密码凭证模式)
请求如下:

curl -X POST -k -H 'Content-Type: application/x-www-form-urlencoded' -i https://localhost:9001/oauth/token --data 'grant_type=password&scope=apiAccess&client_id=client&client_secret=password&username=client&password=password'
  • 注意:上面这种发送方式参数携带客户端的client_id和client_secret这两个,这俩是security-server使用https的客户端认证,(ClientDetailsServiceConfigurer:用来配置客户端详情服务中的配置,保存的密码使用BCryptUtil加密。如果使用其他方式比如jdbc等存储是也需要注意)
/**
     * @param clientDetailsServiceConfigurer
     * ClientDetailsServiceConfigurer:用来配置客户端详情服务(ClientDetailsService)
     * 客户端详情信息在这里进行初始化,你能够把客户端详情信息写死在这里或者是通过数据库来存储调取详情信息。
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clientDetailsServiceConfigurer) throws Exception {
        clientDetailsServiceConfigurer
             .inMemory()//使用方法代替in-memory、JdbcClientDetailsService、jwt
//        client_id: 用来标识客户的Id。第三方用户的id(可理解为账号)
                .withClient("client")
//        client_secret:第三方应用和授权服务器之间的安全凭证(可理解为密码)
                //(需要值得信任的客户端)客户端安全码
                .secret(BCryptUtil.encodePassword("password"))
                .accessTokenValiditySeconds(7200)
                .authorizedGrantTypes("authorization_code", "refresh_token", "client_credentials", "implicit", "password")
                .authorities("ROLE_USER")
                .scopes("apiAccess");
    }
  • 需要注意的是
    或者使用插件(火狐插件RESTClient)


    图片.png
  • 当然如果刚才发送不带client_id和client_secret这两个的话,发送请求后会spring会去认证客户端,所以会让手动输入client_id和client_secret的值

curl -X POST -k -H 'Content-Type: application/x-www-form-urlencoded' -i https://localhost:9001/oauth/token --data 'grant_type=password&scope=apiAccess&username=client&password=password'

有一点我的username和password同client_id和client_secret相同所以可能会导致一些误解,可以在程序硬编码中做修改,如下:

/**
 * @author xzg
 */
@Service
public class BaseUserDetailService implements UserDetailsService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("获取登陆信息:" + username);
//注意:实际生产应该从数据库中获取,用户名,密码(为BCryptPasswordEncoder hash后的密码)
        if (!"zhangsan".equals(username)) {
            logger.error("找不到该用户,用户名:" +username);
            throw new UsernameNotFoundException("找不到该用户,用户名:" + username);
        }
        //密码硬编码
        String password = BCryptUtil.encodePassword("12345");
        // 获取用户权限列表
        List<GrantedAuthority> authorities = CreatHardRole.createAuthorities().get();
        // 返回带有用户权限信息的User
        org.springframework.security.core.userdetails.User user = new org.springframework.security.core.userdetails.User(username,
                password, true, true, true, true, authorities);
        return new BaseUserDetail(new BaseUser(username, password), user);
    }
}

security-server源码


zuul 服务网关

zuul作为边缘路由,这里也属于资源服务,所以重点有两点配置,其一作为资源服务需要配置远程的权限服务器

security:
  oauth2:
    resource:
      userInfoUri: https://localhost:9001/user

同时作为边缘路由,需要配置路由链路

zuul:
    ignoredServices: "*"
    routes:
        restaurantapi:
            path: /api/**
            serviceId: api-service
            stripPrefix: true

其他配置具体可参考源码zuul服务源码
需要说明需要启动本zuul项目,需要依赖eureka server、security-server、rabbitmq、以及其他业务服务

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 151,511评论 1 330
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,495评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,595评论 0 225
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,558评论 0 190
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,715评论 3 270
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,672评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,112评论 2 291
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,837评论 0 181
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,417评论 0 228
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,928评论 2 232
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,316评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,773评论 2 234
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,253评论 3 220
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,827评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,440评论 0 180
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,523评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,583评论 2 249

推荐阅读更多精彩内容