springcloud認証セキュリティ
前の記事:eurekaサーバークラスター
次の記事:Feignを使用して宣言REST呼び出しを実装
し、ユーザー認証をEurekaサーバーに追加する前の例では、Eurekaサーバーは匿名アクセスを許可します。パスワードなしでサービス検出コンポーネントにアクセスできます。ログインしても、dubboにはまだパスワードが必要ですが、これは必要ありません。安全ではないと感じますか?今日は、サービスコンポーネントに認証セキュリティを追加する方法を学びます
eurekaサーバー認証
1 pom.xml
サービスコンポーネントプロジェクトのpom.xmlにspring-boot-starter-securityの依存関係を追加します。この依存関係により、Eurekaサーバーにユーザーを認証する機能が提供されます。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2application.ymlに次のコンテンツを追加します。
spring:
security:
user:
name: root
password: root
これにより、HTTP基本認証がEurekaサーバーに追加されます。このコンテンツが設定されていない場合、アカウントのデフォルトはuserであり、パスワードはランダムな値であり、起動時に出力されます。
3構成ファイルクラスを作成し、認証機能を有効にします
import org.springframework.context.annotation.Configuration;
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;
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable(); //关闭csrf
super.configure(http); //开启认证
}
}
4認証が必要なEurekaサーバーにマイクロサービスを登録します
defaultZone: http://root:root@localhost:8761/eureka/
最後に、application.ymlの内容は次のとおりです。
# 指定该Eureka实例的端口
# enableSelfPreservation是否启动自我保护机制
#server:
# port: 8761
# enableSelfPreservation: true
#eureka:
# client:
# service-url:
# defaultZone: http://localhost:8761/eureka/
# register-with-eureka: false
# fetch-registry: false
spring:
application:
name: discovery-eureka
profiles:
active: peer2
---
spring:
profiles: peer1
security:
user:
name: root
password: root
server:
port: 8761
eureka:
client:
registry-fetch-interval-seconds: 30
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://root:root@peer2:8762/eureka/
---
spring:
profiles: peer2
security:
user:
name: root
password: root
server:
port: 8762
eureka:
client:
fetch-registry: true
register-with-eureka: true
service-url:
defaultZone: http://root:root@peer1:8761/eureka/
プロバイダーおよびコンシューマープロジェクトでの構成
プロバイダープロジェクトとコンシューマープロジェクトの構成ファイルにも、関連する構成情報を追加する必要があります
eureka:
client:
service-url:
defaultZone: http://root:root@peer1:8761/eureka/,http://root:root@peer2:8762/eureka/
instance:
prefer-ip-address: true
このようにして、コンシューマーとサーバーはサービスコンポーネントに登録できます。
テスト
前回の記事ですでに詳しく紹介されているので、しつこくはしません。
もう一度サービスコンポーネントにアクセスします。http:// peer2:8762
は、次の図に示すようにユーザー名とパスワードの入力を求めます。図に示すように
サービスコンポーネントプロジェクトの構成ファイルで構成しない場合
、パスワードは起動時にランダムに生成されるパスワードです。
構成されている場合は、構成ファイルのパスワードです
この認証セキュリティは構成されています