Spring Boot Admin adds alarm reminder and login verification functions!

Posted by onepixel on Thu, 27 Jan 2022 01:38:06 +0100

Spring Boot Admin (SBA) is an open source community project for managing and monitoring Spring Boot applications. It provides detailed health information, memory information, JVM system and environment properties, garbage collection information, log setting and viewing, scheduled task viewing, Spring Boot cache viewing and management, etc.
The overview of SBA monitoring is shown in the figure below:

In the previous article, we talked about the construction and use of SBA. Click to visit: https://mp.weixin.qq.com/s/cciU2u-LXnQHIrHN9uhVYA
However, the above use cannot meet the requirements of our production environment. The production environment needs to be configured with at least the following two functions:

  1. The alarm function of the monitored Spring Boot project, because we can't keep an eye on the SBA monitoring system at all times, but when there is a problem in the system, we need to know it at the first time, so the alarm reminder function is essential.
  2. By default, SBA is used without permission verification, that is, everyone can use it normally after knowing the address, which does not meet the security requirements of the production system, so the user authorization function is also essential.

Next, let's look at the specific implementation of the above functions.

1. Add alarm reminder function

The alarm and reminder function is realized based on the mailbox. Of course, other reminder functions can also be used, such as nail or flying Book Robot reminder, but the realization cost of the mailbox alarm function is the lowest. Therefore, in this paper, we will look at the specific implementation of the mailbox alarm and reminder function.

1.1 add mail support framework

In the SBA dependency file POM Add the following configuration to the XML:

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

1.2 configure receiving and sending mailbox information

In the SBA configuration file application Add the following receiving and sending mailbox configurations in properties:

# Configure send mailbox
spring.boot.admin.notify.mail.from=xxx@qq.com
# Configure receive mailbox
spring.boot.admin.notify.mail.to=xxx@qq.com
# Configure mailbox smtp address (the fixed host of qq sending mailbox is smtp.qq.com)
spring.mail.host=smtp.qq.com
# Configure the mailbox authorization code (here is the authorization code, not the password. Obtaining the authorization code is described in the next step of this article)
spring.mail.password=xxxxxx
# Configure the account name of the mailbox (this is the account name configured above to send mail)
spring.mail.username=xxx@qq.com

1.2.1 enable SMTP service

SMTP is a protocol that provides reliable and effective e-mail transmission. The SMTP service must be enabled for the sending mailbox, otherwise the mail sending function cannot be realized. If the QQ mailbox is used, please refer to the following configuration to open the QQ mailbox, find the IMAP/SMTP service in the account settings of the mailbox and start it, as shown in the following figure:

1.2.2 generate authorization code

Email authorization code should be generated for the sent email. Take QQ email as an example, find "generate authorization code" in the account setting of email and click to generate it, as shown in the following figure:

1.3 mail alarm test

After the above configuration, there is no need to add any code!!! No need to add any code!!! No need to add any code!!! You can realize the email reminder function of project status change.
Let's test it. Close my locally monitored Spring Boot project, and the email will receive the offline information of the project, as shown in the figure below:

After I start the monitored Spring Boot project, the mailbox will receive the server startup email, as shown in the following figure:

In other words, after you configure the receiving and sending mailboxes, Spring Boot Admin will automatically send emails to the mailbox receiving reminders when the monitored project is stopped or started.

1.4 precautions

Precautions for alarm function are as follows:

  1. The mailbox sending mail must have SMTP service enabled.
  2. There is no need to set a password for sending the mailbox. You only need to set the mailbox authorization code for the configuration item "spring.mail.password".
  3. The sending mailbox and receiving mailbox can be the same email address.
  4. There is no need to add any code for the SBA mailbox alarm reminder function, just add the corresponding framework support, and then configure the correct receiving and sending mailbox.

    1.5 configure multiple alarm notification mailboxes

    In general, the alarm function of the project needs to notify a group of relevant principals rather than one person. For example, the operation and maintenance principal, program principal and project manager may be notified. The configuration of SBA multi person reminder mailbox is also easy. You only need to add multiple recipient mailboxes in the SBA configuration file, which are separated by English commas, The configuration is as follows:

    # Configure receive mailbox
    spring.boot.admin.notify.mail.to=xxx@qq.com,yyy@qq.com

    2. Access permission setting

    SBA does not have permission verification by default, and permission verification must be configured in the production environment. Here, we add Spring Security framework to realize permission interception. The specific implementation is as follows.

    2.1 add Security framework support

    In the SBA dependency file POM Add the following configuration to XML:

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

    2.2 setting login account

    In the SBA configuration file application Add the following configuration to properties:

    # Set login user name, password and role
    spring.security.user.name=java666
    spring.security.user.password=java666
    spring.security.user.roles=SBA_ADMIN

    2.3 permission resource settings

    Next, in the SBA project, add the following resource setting classes, as shown in the following code (you can use them directly by copying them into the project):

    import de.codecentric.boot.admin.server.config.AdminServerProperties;
    import org.springframework.context.annotation.Configuration;
    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.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
    import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
    
    @EnableWebSecurity
    @Configuration(proxyBeanMethods = false)
    public class AdminSecurityConfig extends WebSecurityConfigurerAdapter {
     private final String adminContextPath;
    
     public AdminSecurityConfig(AdminServerProperties adminServerProperties) {
         this.adminContextPath = adminServerProperties.getContextPath();
     }
    
     @Override
     protected void configure(HttpSecurity http) throws Exception {
         SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
         successHandler.setTargetUrlParameter("redirectTo");
         successHandler.setDefaultTargetUrl(adminContextPath + "/");
         http.authorizeRequests()
                 .antMatchers(adminContextPath + "/assets/**").permitAll()
                 .antMatchers(adminContextPath + "/login").permitAll()
                 .antMatchers(adminContextPath + "/instances/**").permitAll()
                 .anyRequest().authenticated()
                 .and()
                 .formLogin().loginPage(adminContextPath + "/login").successHandler(successHandler).and()
                 .logout().logoutUrl(adminContextPath + "/logout").and()
                 .httpBasic().and()
                 .csrf()
                 .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                 .ignoringAntMatchers(
                         adminContextPath + "/instances",
                         adminContextPath + "/actuator/**"
                 );
     }
    
     @Override
     public void configure(WebSecurity web) {
         web.ignoring().antMatchers("/actuator/**");
     }
    }

    2.4 access to SBA

    At this time, you need to enter the user name and password to access the SBA monitoring system, as shown in the following figure:

    We can log in by entering the user name and password set in step 2.2, as shown in the figure below:

    Click logout to exit the SBA system.

    summary

    The SBA alarm reminder function only needs to add an email sending framework and configure the correct email receiving and sending. The alarm reminder function can be realized without adding any code, and multiple email boxes for alarm reminder can be configured. SBA can realize the permission verification of users by adding Spring Security.

Right and wrong are judged by ourselves, bad reputation is heard by others, and the number of gains and losses is safe.

The official account: Java interview

Interview collection: gitee.com/mydb/interview

Topics: Spring Spring Boot Back-end