Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities

This paper has participated inProject DigginTo win the creative gift package and challenge the creative incentive money.

📖 preface

Good attitude, not so tired. In a good mood, all you see is beautiful scenery.Copy the code

"If you can't solve a problem for a while, use this opportunity to see your limitations and put yourself out of order." As the old saying goes, it's easy to let go. If you are distracted by something, learn to disconnect. Cut out the paranoia, the trash in the community, and get rid of the negative energy. Good attitude, not so tired. In a good mood, all you see is beautiful scenery.

🚓Add spring-boot-starter-Security initiators to your dependencies:


usespringboot-adminCarry on the projectHealth monitoringThe operation of etc, divided into two parts,Server and client, the server monitors the client, which is your project

Ps: We’re going to be rightadminAdding a Monitoring modulesecurityTo do permission filtering and some interface control to make sure that ouradminUnceremoniously exposed in front of the eyes of others,jasyptIs used toymlSome access passwords and accounts in files are salted and encrypted to ensure security. Therefore, we introduce the following dependencies and configure them.

1. Introduce dependencies as follows:

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

<! Mysql > introduce database password encryption -->
<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>3.0.3</version>
</dependency>
Copy the code

About 2.jasyptThe encryption

# jasypt password encryption configuration
jasypt:
  encryptor:
    It is recommended to read the encrypted salt value in the SpringBoot Application runtime environment
    password: ${JASYPT_ENCRYPTOR_PASSWORD}
    # Encryption algorithm set after 3.0.0
    algorithm: PBEWithMD5AndDES
    iv-generator-classname: org.jasypt.iv.NoIvGenerator
Copy the code

About 3.security çš„ ymlconfiguration

Basically is the login user name and password remember to use firstjasyptEncrypt it

spring:
  application:
    # app name
    name: dream-monitor
  # security Security configuration
  security:
    user:
      name: ENC(kcectA4qZ4IDk793wgLXlA==)
      password: ENC(bEBsIS85g93TCVSnl5ULe3utFwTTeGwB)
  Allow overriding bean definitions
  main:
    allow-bean-definition-overriding: true
  cloud:
    nacos:
      config:
        server-addr: ${spring.cloud.nacos.discovery.server-addr}
        group: DEFAULT_GROUP
        namespace: # namespaces
        enabled: true
        encode: UTF-8
        username: nacos
        # nacos password
        password: ENC(eRxrrhJffCFgrinBTO3lPzQIkso6IZlB)
        max-retry: 32
        file-extension: yml
      discovery:
        server-addr: # nacos address
Copy the code

About 4.security çš„ configconfiguration

package com.cyj.dream.visual.monitor.config;

import de.codecentric.boot.admin.server.config.AdminServerProperties;
import io.swagger.models.HttpMethod;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

/ * * *@Description: Web permission configuration *@BelongsProject: DreamChardonnay
 * @BelongsPackage: com.cyj.dream.visual.monitor.config
 * @Author: ChenYongJia
 * @CreateTime: 2021-09-29
 * @Email: [email protected]
 * @Version: 1.0 * /
@Slf4j
@Configuration
@Order(0)
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    private final AdminServerProperties adminContextPath;

    public WebSecurityConfigurer(AdminServerProperties adminContextPath) {
        this.adminContextPath = adminContextPath;
    }

    /** * WebSecurity permission configuration **@paramHTTP permission HTTP *@return
     * @author ChenYongJia
     * @date2021/9/29 * /
    @Override
    //@SneakyThrows
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setTargetUrlParameter("redirectTo");
        successHandler.setDefaultTargetUrl(this.adminContextPath.getContextPath() + "/");

        // Configure allowed requests and cross-domain issues
        http.authorizeRequests()
                .antMatchers(this.adminContextPath.getContextPath() + "/assets/**").permitAll()
                // All requests are accessible, and local development opens the comment on the following line
                //.antMatchers("/**").permitAll()
                // Requests or resources without permission validation (read from configuration files), local development can, comment out this line
                .antMatchers(this.adminContextPath.getContextPath() + "/login").permitAll()
                .antMatchers("/ * *")
                .fullyAuthenticated()
                .and()
                .csrf()
                .disable()
                // Set the login address
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                // Configure the logout address
                .logout()
                // /userInfo/loginOutByToken
                .logoutUrl("/logout")
                .and()
                // Enable cross-domain
                .cors()
                .and()
                // Cancel cross-site request forgery protection
                .csrf()
                .ignoringRequestMatchers(
                        new AntPathRequestMatcher(this.adminContextPath.getContextPath() +
                                "/instances", HttpMethod.POST.toString()),
                        new AntPathRequestMatcher(this.adminContextPath.getContextPath() +
                                "/instances/*", HttpMethod.DELETE.toString()),
                        new AntPathRequestMatcher(this.adminContextPath.getContextPath() + "/actuator/**"))
                .disable();
        // @formatter:on
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/actuator/**"); }}Copy the code

5. serverStart the

And then you can go directly to the launch, access your SettingsIP/portIt jumps to the login page and entersThe account passwordYou can see the forgiving coloradminBut no clients are being monitored at this pointclient 端

6. clientThe end is actually very simple

Here in the last article has been written you can refer to the seventh chapter:Microservices SpringCloud project (7) : integration of Spring-boot-Admin monitoring

    <dependency>
        <groupId>de.codecentric</groupId>
        <artifactId>spring-boot-admin-starter-client</artifactId>
        The < version > 2.1.1 < / version >
    </dependency>
Copy the code

PS:The recent output of the article to the practical resistance to build, I hope to help you rather than a long story is all theoretical combat weak chicken, finally thank you for your patience to watch the end, leave a thumbs-up collection is your biggest encouragement to me!


🎉 summary:

  • For more references, see here:The Blog of Chan Wing Kai

  • Like the small partner of the blogger can add a concern, a thumbs-up oh, continue to update hey hey!