Step by step to learn spring security Part 2, how to modify the default user?

Review the previous article

In the last article "[Don't say that you are not familiar with spring security in the interview, a demo will make you try to fool the interviewer] (https://blog.csdn.net/huangxuanheng/article/details/119062001)" In the spring security With a preliminary feeling, next, let's analyze the user configuration together

When the previous project starts, it will automatically print out the password of the default user. This password is a temporary password, and the user is also the default user user. However, in actual projects, users are often obtained from the database, but don’t worry, we Step by step to understand spring security.

Source code download

How to configure users?

So here comes the question, I am not familiar with spring security, I don’t understand anything, how do I get started? How to configure users? Don't forget, after our last project runs, it will automatically print out the default user's password
insert image description here
. generated security password” to search the entire project for follow-up, as expected, after following up, I found the print log code,
insert image description here
so I continued to follow up the User class, and found that this is a configuration class SecurityProperties
insert image description here

The default user is user, and the default temporary password is a random password generated by UUID. The
default user is defined in it, which is a static internal class. If we want to define our own username and password, we must override the default configuration. Let's first look at the definition of SecurityProperties, which is very clear. We only need to prefix spring.security.user to define the username and password.

The username and password defined in properties are finally injected into the property through the set method. Here we take a look at the SecurityProperties.User#setPassword method: from here we can see
insert image description here
that the password defined in application.properties is being injected. After that, the passwordGenerated property is also set to false by the way. After this property is set to false, the console will not print the default password.

At this point, restart the project, and you can log in with your defined username/password.

Now that we know this configuration, let’s look at the code to see the effect

New Project

  • Create a new spring boot project named security-userconfig, choose to rely on spring security and spring web
    to add maven dependencies
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

insert image description here

  • Create a new HelloController class
@RestController
public class HelloController {
    
    

    @RequestMapping("/sayHello")
    public String sayHello(){
    
    
        return "十年生死两茫茫,不思量,自难忘----苏轼,hello";
    }
}

  • Add the default user and password configuration items. I am used to changing the extension name of the configuration file to yml format. After completion, it is as follows
spring:
  security:
    user:
      name: harry
      password: 123456


test

  • Start the project and find that the temporary password printed by default is no longer printed, which is consistent with the above analysis
    insert image description here

  • Access interface: http://127.0.0.1:8080/sayHello, it will automatically adjust to the login page, enter the user name in the configuration: harry, password: 123456, click login, and the login is successful! Indicates that the default user and password we configured through the configuration file are correct

Configure users in code

Above we introduced the way to configure the default user and default password through the configuration file, but in the actual development process, our users are read from the code, and then we configure the user through the code

  • Create a new class SecurityConfig, inherit WebSecurityConfigurerAdapter, and implement the corresponding configuration
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    
    @Bean
    PasswordEncoder passwordEncoder() {
    
    
        return NoOpPasswordEncoder.getInstance();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    
    
        auth.inMemoryAuthentication()
                .withUser("harry")
                .password("123456").roles("user");
    }
}

illustrate:

  • PasswordEncoder is a password encryption interface, because we are step by step, I will use the non-encrypted instance first
  • Implement the configure(AuthenticationManagerBuilder auth) configuration method. For the convenience of the diagram, I first create the default user harry in memory, the default password is 123456, and the role is user
  • The default user and default password in the configuration file are commented out
  • Start the project, access the interface test, and find that it is like this after logging in.
    insert image description here
    In fact, the login is successful, and the access verification can be successful by entering the interface again

But why does it jump to this page after successful login? We’ll talk about this later, let’s stop here for today!

Source code download

Guess you like

Origin blog.csdn.net/huangxuanheng/article/details/119064244