Springsecurity authentication integrating springboot version 6.0.2

If you want to integrate Spring Security for authentication in a Spring Boot 6.0.2 project, you need to perform the following steps:

  1. Add dependencies: In your project's pom.xml file, add the following dependencies:
<dependencies>
    <!-- Spring Security -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
</dependencies>

  1. Create a configuration class: Create a configuration class named SecurityConfig, which needs to inherit WebSecurityConfigurerAdapter and override the configure method. In the configure method, you can configure authentication rules and permission control, etc.
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/public").permitAll()
                .antMatchers("/private").authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }
}

In the above example, permission control for two access paths is configured. The /public path allows all users to access, and the /private path requires authentication before access. In addition, the login page and logout configuration are configured.

  1. Create a login page: Create a login page named login.html in the static resource directory (default is src/main/resources/static).

  2. Configure user information: In the configuration class, you can configure user information by overriding the configure method and using AuthenticationManagerBuilder.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password(passwordEncoder().encode("password")).roles("USER");
    }
    
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

In the above example, a user with the user name and password password is configured, and its role is specified as USER.

  1. Run the application: Start your Spring Boot application and access the corresponding URL to test.

The above is an example of basic Spring Security authentication integration steps. You can configure and customize it according to your business needs.

Guess you like

Origin blog.csdn.net/m0_37649480/article/details/135464668