这篇文章主要为大家展示了“Spring Cloud怎么保证微服务内安全”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“Spring Cloud怎么保证微服务内安全”这篇文章吧。
在微服务的架构下,我们需要把系统的业务划分成多个单一的微服务。每个微服务都会提供接口供其他微服务调用,在Dubbo中可以通过rmi、nio等实现,Spring Cloud中是通过http调用的。
但有些时候,我们只希望用户通过我们的网关调用微服务,不允许用户直接请求微服务。这时我们就可以借助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 此时访问接口发现已经需要认证了。
输入正确的账号和密码后就可以访问了。
1 在application.yml中配置账号密码
security:
user:
name: sunbufu
password: 123456
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 这样完成后,就可以正常的访问了。
git源码地址:https://github.com/sunbufu/sunbufu-cloud
1. sunbufu-erueka:Eureka服务的工程
2. sunbufu-hello-face:服务接口的定义工程,其中包括定义微服务需要实现什么功能,其他微服务怎么调用,以及feign的配置
3. sunbufu-hello-impl:服务接口的实现工程,实现了sunbufu-hello-face定义的功能
4. sunbufu-hello-web:服务的网关工程,主要为了调用sunbufu-hello-face
Spring Cloud可以增加HTTP Basic认证来增加服务连接的安全性。
在maven配置文件中加入Spring Boot的security启动器。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
这样,就开启对服务连接的安全保护,系统默认为生成一个用户名为”user”及一个随机密码,随机密码在服务启动的时候在日志中会打印出来。
随机密码没什么实际意义,我们需要一个固定的连接用户名和密码。
在应用配置文件中加入以下配置即可。
security:
user:
name: admin
password: admin123456
这样配置完后在连接这个服务的时候就会要求输入用户名和密码,如果认证失败会返回401错误。
{
"timestamp": 1502689874556,
"status": 401,
"error": "Unauthorized",
"message": "Bad credentials",
"path": "/test/save"
}
1、注册中心安全连接
username:password@ipaddress
2、Feign申明式服务安全连接
@FeignClient(name = "SERVICE", configuration = FeignAuthConfig.class)
public interface OrderService extends OrderAPI {
}
@Configuration
public class FeignAuthConfig {
@Bean
public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
return new BasicAuthRequestInterceptor("admin","admin123456");
}
}
以上是“Spring Cloud怎么保证微服务内安全”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。