Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to analyze Spring Cloud Config configuration

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

Today I'll show you how to analyze the Spring Cloud Config configuration. The content of the article is good. Now I would like to share it with you. Friends who feel in need can understand it. I hope it will be helpful to you. Let's read it along with the editor's ideas.

Spring Cloud Config Server configuration Service

Spring is an extension configuration service that provides an api for resource binding based on HTTP. (key-value pairs, or YAML content) this service can be easily integrated into Spring Boot applications through @ EnableConfigServer.

For example: ConfigServer.java

@ SpringBootApplication@EnableConfigServerpublic class ConfigServer {public static void main (String [] args) {SpringApplication.run (ConfigServer.class, args);}}

By default, it runs on port 8080 like Spring Boot applications, and there are many ways to modify this port. The easiest way is to set the default configuration repository. By configuring spring.config.name=configserver; in the configserver.yml file in jar or by specifying your own configserver.yml.

For example: application.properties

Server.port: 8888spring.cloud.config.server.git.uri: file://${user.home}/config-repo

${user.home} / config-repo, is a git resource. The content is the content of YAML or properties file.

For example:

$cd $HOME$ mkdir config-repo$ cd config-repo$ git init. $echo info.foo: bar > application.properties$ git add-A. $git commit-m "Add application.properties"

Note: the above use of local files is only for testing. Configuration resources provided by remote services should be used in production.

1 Environment Repository environmental resources

How do you want to store configuration data in Config Server? The storage policy is determined by EnvironmentRepository in Environment. At the same time, it is also allowed to copy configuration items between multiple Environment, and even configure the source propertySources.

Environment resources mainly come from these three parameters:

{application} corresponds to the client's spring.application.name configuration

{profile} corresponds to client spring.profiles.active configuration

{label} this is a server-side feature that marks the version of the configuration file.

Resource instances usually behave like Srping Boot application load configuration files: spring.config.name is similar to the {application} parameter; spring.profiles.active is similar to the {profiles} parameter. The priority of a particular profile is similar to that of Spring Boot: a specific configuration overrides the default configuration, and if more than one is specified, the last one has the highest priority.

For example, a client application can configure the boot configuration:

Bootstrap.yml

Spring: application: name: foo profiles: active: dev,mysql

Ordinary Spring Boot applications can also configure the above information through environment variables or command line.

If the resource is file-based, the system creates an Environment from application.yml to share with all clients, and loads foo.yml to overwrite it. If specific configurations are specified in the YAML file, these specific configurations have a higher priority than the default configuration. These configuration files with higher priority are generated and loaded one by one before Environment.

1.1 Git Backend is based on GIT

By default, EnvironmentRepository is based on GIT, which makes it easy to manage updates and the physical environment to audit the modification history. The local repository of Config Server can be modified through the spring.cloud.config.server.git.uri configuration properties (for example, in application.yml). If set to file: prefix, it will be loaded from local resources, which makes it easy to start the service quickly and easily. But this is done directly on the local repository without backup. (however, if the remote service resource is not changed, this approach does not matter. )

If you need to extend Config Server to make it highly available, you need to point all service instances to the same resource so that you work in a shared file environment. In this case, it is best to use the ssh: protocol to access shared file resources, so that resources can be backed up and local caching can be used to improve efficiency.

The resource instance will map the {label} in the HTTP resource to the git tag (commit id, branch name or tag). If the git branch or signature has a slash "/", it will be automatically replaced with "_" when it is mapped to HTTP URL. Be careful when using parentheses and spaces. (for example, double quotation marks are required when using cmd)

1.1.1 Placeholders in Git URI: placeholders in git uri

Spring Cloud Config Server supports the use of {application}, {profile}, and {label} placeholders in GIT URI when needed, but keep in mind that {label} always maps to git tags.

Spring: cloud: config: server: git: uri: https://github.com/myorg/{application}1.1.2 Pattern Matching and Multiple Repositories regular and multi-resource libraries

Regular expressions can be passed in both the application profile and the specific profile to support more complex situations. You can use wildcards in {application} / {profile} to match, and if there are multiple values you can use commas to separate them.

Spring: cloud: config: server: git: uri: https://github.com/spring-cloud-samples/config-repo repos: simple: https://github.com/simple/config-repo special: pattern: special*/dev* * special*/dev* uri: https://github.com/special/config-repo local: pattern: local* uri: file:/home/configsvc/config-repo

If {application} / {profile} does not match any resources, the default URI configured by spring.cloud.config.server.git.uri is used.

In the above example, the pattern attribute is an YAML array, which can also be defined using the YAML array format. This can be set to multiple configuration files.

Spring: cloud: config: server: git: uri: https://github.com/spring-cloud-samples/config-repo repos: development: pattern:-* / development-* / staging uri: https://github.com/development/config-repo staging : pattern:-* / qa-* / production uri: https://github.com/staging/config-repo

Each repository has an optional configuration to specify the scan path.

Spring: cloud: config: server: git: uri: https://github.com/spring-cloud-samples/config-repo searchPaths: foo,bar*

The system automatically searches for subdirectories of foo, as well as subdirectories in folders that start with bar.

By default, the system replicates the remote repository when configuration is first requested. The system can also be configured to copy remote repositories as soon as they are started.

Spring: cloud: config: server: git: uri: https://git/common/config-repo.git repos: team-a: pattern: team-a-* cloneOnStart: true uri: http://git/team-a/config-repo.git team-b: Pattern: team-b-* cloneOnStart: false uri: http://git/team-b/config-repo.git team-c: pattern: team-c-* uri: http://git/team-a/config-repo.git

In the above example, team-a 's repository is replicated from the remote repository at startup, while others are not replicated from the remote repository until the first request.

If the remote repository has permission authentication set, it can be configured as follows:

Spring: cloud: config: server: git: uri: https://github.com/spring-cloud-samples/config-repo username: trolley password: strongpassword

If you are not using HTTPS and user authentication, you can use the SSH uri format. For example: git@github.com:configuration/cloud-configuration so you need to have SSH's key first. In this way, the system will use the JGit library for access, you can view the relevant documents. You can set the HTTPS proxy configuration in ~ / .git / config, or you can configure the proxy with the JVM parameters-Dhttps.proxyHost,-Dhttps.proxyPort.

Tip: when you don't know your ~ / .git directory, you can use git config-- global to specify it. For example: git config-- global http.sslVerify false

3.2.1.1.3 Placeholders in Git Search Paths: placeholders in GIT path search

Spring Cloud's Config Server also supports the use of {application}, {profile}, and {label} placeholders in the search path. For example:

Spring: cloud: config: server: git: uri: https://github.com/spring-cloud-samples/config-repo searchPaths:'{application} '1.2 File System Backend is based on the file system

There is also a way not to use the git repository, which is to load configuration files from the local classpath or file system. This method can be enabled through spring.profiles.active=native.

Use the file: prefix to load the file system, otherwise from classpath, you can also use a ${} style environment placeholder. For example: file:///${user.home}/config-repo

The default value of searchLocations is the same as the scan path of the local Spring Boot application: [classpath:/, classpath:/config, file:./, file:./config] so you don't have to worry about exposing the application.properties file to all clients, because it will be cleaned up before it is sent to the client.

File system-based configuration services are good for testing and quick practice, and if used in a production environment, you need to ensure the reliability of the file system and allow shared access.

Path search can include {application}, {profile}, {label}, which makes it easy for you to manage your configuration files by directory.

If you do not use placeholders in the path search, you will also try to automatically add the {label} suffix to the HTTP resource, which will be loaded into from different paths. Therefore, not using placeholders by default is equivalent to adding / {label} / after each path. For example: file:/tmp/config is equivalent to file:/tmp/config,file:/tmp/config/ {label}

1.3 Sharing Configuration With All Applications Application sharing configuration

Through file-based (svn, local) resources, resources with the file name application* will be shared among all application clients. (application.properties,application.yml,application-*.properties) A global default configuration can be defined in this way, and applications can override it with the application-specified configuration if necessary.

1.4 Property Overrides attribute override

Config Server has a property override feature that allows operators to override configurations in all applications by providing a configuration property. This is done through normal Spring Boot hooks, so the application doesn't need to change much.

Declaring overrides requires only one key-value pair to be configured in spring.cloud.config.server.overrides. For example:

Spring: cloud: config: server: overrides: foo: bar

This will cause all application clients to read foo=bar to overwrite their own configuration. (of course, after the application gets the new data, it decides how to use it. Therefore, overwriting is not mandatory, and the client can customize the behavior after getting the new data.)

Tip: when using file mode, the placeholder ${} in the Spring environment can be escaped with "" to "$", for example:\ ${app.foo:bar}. When using YAML, the YAML itself handles it, so there is no need to escape.

2.2 Health Indicator Health indicator

Config Server uses a health indicator to detect whether the configured EnvironmentRepository is working properly. By default, EnvironmentRepository is asked for an application configuration named app, and the EnvironmentRepository instance responds to the default configuration.

You can use configuration to have health indicators check multiple configurations for multiple applications. For example:

Spring: cloud: config: server: health: repositories: myservice: label: mylabel myservice-dev: name: myservice profiles: development

You can also disable this feature by configuring spring.cloud.config.server.health.enabled=false.

2.2 Security Security

You can safely handle Config Server in any way you like. (from physical network security to OAuth3 authorized token), but combining Spring Security with Spring Boot provides a better way.

Using Spring Boot's default HTTP-based security approach, you only need to introduce Spring Security dependencies. (for example, you can use spring-boot-starter-security)

It is not very reliable to use a user name and a randomly generated password by default, so it is recommended that you configure the password through spring-boot-starter-security and encrypt it.

2.3 Encryption and Decryption encryption and decryption

Important: to use this feature, full JCE authorization is required, as described earlier

If the remote resource is an encrypted content (starting with {cipher}), it will be decrypted before it is sent to the client. In this way, the configuration content does not need to be stored in clear text. When you directly replace an undecrypted value, it is marked as "invalid" (invalid). This can basically put an end to the occurrence of key disclosure. For example:

Application.yml

Spring: datasource: username: dbuser password:'{cipher} FKSAJDFGYOS8F7GLHAKERGFHLSAJ'

If you use a configuration file, encrypt the data without double quotes. For example:

Application.properties

Spring.datasource.username: dbuserspring.datasource.password: {cipher} FKSAJDFGYOS8F7GLHAKERGFHLSAJ

This allows you to share this file securely while protecting the key.

This service is exposed through / encrypt and / decrypt endpoints. In this way, the encrypted data can be submitted to / encrypt in POST mode. For example:

$curl localhost:8888/encrypt-d mysecret682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda

Vice versa, submit data securely through / decrypt. (provided that the corresponding decryption KEY has been configured on the server)

$curl localhost:8888/decrypt-d 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bdamysecret

It is potentially insecure to store this encrypted data before submitting it.

Both / encrypt and / decrypt accept a path / * / {name} / {profiles} to control the password of each application separately.

Note: if you need to use a different password for each application, you need a @ Bean to generate a TextEncryptorLocator object to create different key pairs and give them a name. Of course, this is optional, which is not required by default (all applications use the same key)

The Spring command line client (Spring Cloud CLI) can also use the encryption and decryption feature. For example:

$spring encrypt mysecret-key foo682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda$ spring decrypt-key foo 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bdamysecret

You can use @ to specify a path that contains a file that holds the encryption and decryption key. For example:

$spring encrypt mysecret-- key @ ${HOME} / .ssh/id_rsa.pubAQAjPgt3eFZQXwt8tsHAVv/QHiY5sI2dRcR+...2.4 Key Management key management

Config Server can use symmetric / asymmetric encryption and decryption algorithms. Using asymmetric algorithms has better security, but symmetric algorithms are more convenient.

To configure the key of the symmetric algorithm, you only need to set encrypt.key. (or use the environment variable ENCRYPT_KEY)

Configure the asymmetric algorithm key, you can choose to configure a PEM-encoded text in encrypt.key, or you can use a KeyStore through encrypt.keyStore.* configuration.

Encrypt.keyStore.* includes the following configurations:

Location one resource path

Password KeyStore password

Identification of the key used by alias

Through public key encryption, private key decryption. Therefore, in principle, only the public key can be configured on the server side. However, this may be rarely done in practice, and key management is included in all client processes, not just on the server side. On the other hand, if the server is really insecure and only a few clients need to be encrypted, then this configuration is reasonable.

2.5 Creating a Key Store for Testing create a KeyStore for testing

You can create a KeyStore for testing with the following configuration:

$keytool-genkeypair-alias mytestkey-keyalg RSA\-dname "CN=Web Server,OU=Unit,O=Organization,L=City,S=State,C=US"\-keypass changeme-keystore server.jks-storepass letmein

Put the server.jks file into classspath, and then configure the following in application.yml:

Encrypt: keyStore: location: classpath:/server.jks password: letmein alias: mytestkey secret: changeme2.6 Using Multiple Keys and Key Rotation uses multiple keys and key rotation

By adding the {cipher} prefix to indicate the use of encrypted data, the system looks for the {name:value} prefix information before Base64 decoding the ciphertext. The key passes through the TextEncryptorLocator (either way) instance, and finally uses TextEncryptor to complete the encryption and decryption. If the KeyStore (encrypt.keystore.location) is configured, the default executor (locator) will look for the corresponding key in the KeyStore according to the configured alias. For example:

Foo: bar: `{cipher} {key:testkey}...`

In the above example, the executor (locator) will look for a key called "testkey". The password of the KeyStore can be obtained through {secret:... } to specify, but not if not necessary. If you want to use a KeyStore password, it is recommended that you use a custom SecretLocator to encrypt it.

Key rotation is basically unnecessary if only a small amount of configuration data is encrypted. However, there are still scenarios where I still need to modify the key. In this case, all clients need to change the source configuration file (such as: git) to use the new {key:... }, it is also best to check the keys in the KeyStore in advance.

Tip: {name:value} can also be used in / encrypt data requests.

2.7 Serving Encrypted Properties provides encryption properties

Sometimes it is necessary for the client to decrypt the configuration number, rather than decrypting it on the server. In this case, it can still be accessed through / encrypt and / decrypt endpoints. Then you need to explicitly specify that the configuration data is not decrypted when it is sent from the server: spring.cloud.config.server.encrypt.enabled=false. If it is not related to endpoint access, then neither configure the key nor turn on this configuration.

The above is how to analyze the whole content of Spring Cloud Config configuration, more content related to how to analyze Spring Cloud Config configuration can search the previous articles or browse the following articles to learn ha! I believe the editor will add more knowledge to you. I hope you can support it!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report