Spring Cloud 学习之Eureka(3) —— 提供安全保障

Spring Cloud 学习之Eureka(1) —— 单机模式

Spring Cloud 学习之Eureka(2) —— 集群模式

上一篇我们完成了集群化部署,一般来说,注册中心基本就到此结束了,但是Eureka Server和Eureka Client之间是通过http方式来维护心跳的,所以可能被抓取到资源包,从而冒充请求,非法访问注册中心,所以我们需要对注册中心加入安全策略,这里我用的是Spring Security这个安全框架,虽然这个框架非常笨重,但是结合springboot后,使用非常方便,所以我们就用它来实现安全策略。

首先在pom文件中引入Spring Security的依赖:

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

然后创建Security的配置文件,我们这里拦截所有请求:

package com.maochd.springcloud.eureka.service.config;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.NEVER)
                .and()
                .csrf()
                .disable()
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .httpBasic();
    }
}

接下来我们在yml文件中创建账户,我创建了一个maochd的用户:

server:
  port: 28080

spring:
  application:
    name: maochd-eureka-server
  security:
    user:
      name: maochd
      password: maochd
      roles: SERVICE_NODE
      
eureka:
  instance:
    hostname: maochd-eureka-server1
  client:
    service-url:
      defaultZone: http://maochd-eureka-server2:28081/eureka
#    fetch-registry: false
#    register-with-eureka: false

由于引入的安全框架,所以我们需要在注册中心的路径上配置上用户名密码,例如

## example http://username:password@hostname:port/eureka
http://maochd:maochd@maochd-eureka-server2:28082/eureka/

这样我们就跟集群化时是一样的了,接下来我们启动注册中心,访问注册中心控制台,这时候会跳出登录表单,说明安全框架生效了,我们输入新创建的账号,即可正常进入:

接下来我们把所有的defaultZone都加上用户名密码,就可实现安全控制了。

按照集群化部署的方式启动,等所有服务都成功运行后,刷新注册中心,便可看到所有服务已经被注册了:

如果不加用户名,服务就会报错:

然后我们访问一下接口:

发现引入安全策略并不影响接口调用,只是保证了注册中心的安全。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值