Configuration-based User Name Password Settings and Scenario Description

spring-security basic configuration username password

Scenarios applicable

Configure the basic user password instead of checking it dynamically through a database, etc. Generally speaking, it is suitable for simple scenarios, such as adding a base-based authentication to eureka;

Infrastructure Project Setup

Build a maven project based on the following configuration file and start the springboot project to complete the combination of springboot +spring security;
pom file reference:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>spring-security-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-parent</artifactId>
                <version>2.3.6.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
    </dependencies>
</project>

Start the project and observe what's in the log:

In the log above, the temporary password will be printed.

Default configuration description (dynamic password)

  • When spring security is introduced, the security module is turned on by default, and all requests are intercepted by default without any configuration.
  • Default username: user, the password is generated automatically for each boot and is available in the log.
  • Default login page:

Configure User Name Password with Profile

Modify the project configuration file, such as: application.yml, add the following configuration:

spring:
  security:
    user:
      name: admin
      password: admin

Restart the project, at which point the console no longer displays the password, using the username password in the matching file to complete the login
***Description: ***
This scenario applies to scenarios such as Eureka that require temporary authentication, such as production environments that require control over project encryption codes such as eureka, by introducing a security module and configuring the configuration file (the configuration file is not public if required). Of course, additional configurations are needed. Here's a simple idea

    1. Configure username password and turn on Http basic authentication (no configuration is required after security 5.x)

The reference configuration is as follows:

spring:
  security:
   # Turn on basic authentication (obsolete, may not be set after configuring user information, turn on by default)
    basic:
      enibled: true
    # Set authentication information
    user:
      password: eureka
      name: eureka
    1. Configure Authentication Content
      The reference code is as follows:
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
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().frameOptions().disable();
        // Turn off csrf, set authentication (/actuator/** begins without authentication, everything else needs) httpBasic() turns on basic authentication, which is not required by default
        http.csrf().disable().authorizeRequests().antMatchers("/actuator/**").permitAll().anyRequest().authenticated().and().httpBasic();
        // Turn off basic authentication sample code:
        // http.authorizeRequests().anyRequest().authenticated().and().httpBasic().disable();
    }
}
    1. Example microservice registration eureka configuration file
      For microservices that need to be registered with eureka, simply modify the Eureka address, which is the basic authentication method.
      The reference configuration is as follows:
eureka:
  client:
    serviceUrl:
     # basic authentication url: protocol: //username: password@ip: port/resource address
      defaultZone: http://eureka:eureka@localhost:8000/eureka/

Configure username passwords by configuring classes

This scenario has fewer scenarios and is suitable for code implementation in scenarios where the configuration file is not clear text.

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//   Turn off basic authentication
//    @Override
//    protected void configure(HttpSecurity http) throws Exception {
//        //Turn off basic authentication
//        // http.authorizeRequests().anyRequest().authenticated().and().httpBasic().disable();
//    }
// Profile-based authentication
    @Override
    protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        // Password Encryption
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String password = bCryptPasswordEncoder.encode("admin1");
        // Configure authentication information
        authenticationManagerBuilder.inMemoryAuthentication().passwordEncoder(bCryptPasswordEncoder).withUser("admin").password(password).roles("roleA");
    }
}


summary

The above three authentication information settings have limited scenarios and can be used as a fast implementation scheme. Attention should be paid to distinguishing the applicable scenarios.

The above content source location: https://gitee.com/master336/spring-security-demo/tree/basic

Keywords: Java Spring Spring Boot spring-security

Added by busnut on Wed, 26 Jan 2022 09:31:00 +0200