Memory-based authentication for SpringBoot integration with SpringSecurity

Keywords: Spring SpringBoot github

Memory-based authentication for SpringBoot integration with SpringSecurity (1)

In the first tutorial, we simply learned how to use SpringSecurity, added dependencies, and added a few lines of configuration to the application.yml file to achieve a basic login authentication.

The default configuration can only set one account, so how can I support multiple accounts?

This article describes memory-based authentication

I. Memory authentication

Based on how authentication information is stored in memory, this post introduces two common usage positions

0. Project Configuration

Configuration of the environment is consistent with the previous one, and you can refer to the blog post for more information: Origin of 191223-SpringBoot Integration SpringSecurity (Zero)

1. WebSecurityConfigurerAdapter

This is handled primarily through SpringSecurity's configuration adapter, and here is a simple case

@Configuration
public class SecurityAdapterConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // When testing, you can use the following methods directly
        //        User.UserBuilder builder = User.withDefaultPasswordEncoder();
        User.UserBuilder builder = User.builder().passwordEncoder(passwordEncoder()::encode);
        auth.inMemoryAuthentication().withUser(builder.username("hui1").password("123456").roles("guest").build());
        auth.inMemoryAuthentication().withUser(builder.username("hui2").password("123456").roles("guest").build());
    }
}

The main logic is in the configure method, but it's important to note that we've added an extra way to encrypt passwords. When we don't set this up, when we actually log in, we'll find that even if you've entered the correct username password, you'll be prompted to fail (guys are welcome to check it out)

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

Second, when creating users, it is important to note that in addition to setting the user name and password, users are given a role, which will be described in a subsequent article on RBAC (Role-based Authorization)

2. UserDetailsService

Another way to save authentication information in the subsequent db is described here; in the implementation of Spring Security, the user information is queried by the user name through the UserDetailService Bean; so we can achieve our goal by simply implementing a custom Bean instead of the default one

Our configuration classes are as follows

@Configuration
public class SecurityAutoConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * Memory-based authentication
     *
     * @param passwordEncoder
     * @return
     */
    @Bean
    public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
        User.UserBuilder users = User.builder().passwordEncoder(passwordEncoder::encode);
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(users.username("1hui").password("123456").roles("guest").build());
        manager.createUser(users.username("2hui").password("666666").roles("manager").build());
        manager.createUser(users.username("3hui").password("root").roles("admin").build());
        return manager;
    }
}

3. Testing

Both of the above methods can save authentication information in memory. Next, let's go into the testing phase and write an http interface first

@RestController
public class IndexRest {

    public String getUser() {
        // Get user information
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        String userName;
        if (principal instanceof UserDetails) {
            userName = ((UserDetails) principal).getUsername();
        } else {
            userName = principal.toString();
        }
        return userName;
    }

    /**
     * @return
     */
    @GetMapping(path = {"/"})
    public String index() {
        return "hello this is index! welcome " + getUser();
    }
}

In the actual test, both of the above case s are ok, and the demo below is based on the example given in the second way.

II. Other

0.Series Blog & Project Source

Bowen

Source code

1.A grey Blog

Unlike letters, the above are purely family statements. Due to limited personal abilities, there are unavoidable omissions and errors. If bug s are found or there are better suggestions, you are welcome to criticize and correct them with gratitude.

Below is a grey personal blog, which records all the blogs in study and work. Welcome to visit it

186 original articles published. 49. 140,000 visits+
Private letter follow

Posted by FeeBle on Tue, 14 Jan 2020 17:41:47 -0800