Spring Cloud 保证微服务内安全

Spring Cloud 保证微服务内安全

2018年02月08日 11:41:57 sunbufu 阅读数:2079

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sunbufu/article/details/79287340

一、简介

在微服务的架构下,我们需要把系统的业务划分成多个单一的微服务。每个微服务都会提供接口供其他微服务调用,在Dubbo中可以通过rmi、nio等实现,Spring Cloud中是通过http调用的。但有些时候,我们只希望用户通过我们的网关调用微服务,不允许用户直接请求微服务。这时我们就可以借助Spring Security来保障安全。

二、使用步骤

2.1 在提供接口的微服务项目中配置Spring Security

1 首先在pom.xml引入Spring Security的相关配置,如下

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

2 在qpplication.yml中配置账号密码,如下

security:
  basic:
    enabled: true
  user:
    name: sunbufu
    password: 123456

3 此时访问接口发现已经需要认证了。
需要认证
输入正确的账号和密码后就可以访问了。

2.2在调用微服务项目中配置Feign的账号密码

1 在application.yml中配置账号密码

security:
  user:
    name: sunbufu
    password: 123456
  • 1
  • 2
  • 3
  • 4

2 添加Feign的配置文件

package com.sunbufu.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import feign.auth.BasicAuthRequestInterceptor;

@Configuration
public class FeignConfiguration {

    @Value("${security.user.name}")
    private String userName;

    @Value("${security.user.password}")
    private String passWord;

    @Bean
    public BasicAuthRequestInterceptor basicAuthRequestInterceptor(){
        return new BasicAuthRequestInterceptor(userName, passWord);
    }
}

3 这样完成后,就可以正常的访问了。
正常访问

三、实例

工程介绍

源码地址

下面是这4个工程的说明:
1. sunbufu-erueka:Eureka服务的工程
2. sunbufu-hello-face:服务接口的定义工程,其中包括定义微服务需要实现什么功能,其他微服务怎么调用,以及feign的配置
3. sunbufu-hello-impl:服务接口的实现工程,实现了sunbufu-hello-face定义的功能
4. sunbufu-hello-web:服务的网关工程,主要为了调用sunbufu-hello-face

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值