How Spring Boot uses Spring Security for authentication and authorization

How Spring Boot uses Spring Security for authentication and authorization

Authentication and authorization are very important functions in web applications. Spring Security is a powerful security framework based on the Spring framework, which provides a complete authentication and authorization solution, and can be easily integrated into Spring Boot applications. This article will introduce how to use Spring Security for authentication and authorization in Spring Boot, and provide sample code.

insert image description here

Add Spring Security dependency

First, we need to add the Spring Security dependency to pom.xmlthe file :

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

In the above dependencies, we added spring-boot-starter-securitythe dependency which includes all the necessary dependencies of Spring Security.

Configuring Spring Security¶

Next, we need to configure Spring Security. In a Spring Boot application, Spring Security can be configured using Java configuration or XML configuration. In this article, we will use Java configuration.

We need to create a class SecurityConfigcalled and annotate @EnableWebSecurityit. This annotation enables Spring Security and automatically configures basic web security.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    
    
}

Next, we can override configurethe method to configure Spring Security. For example, we can configure basic authentication and authorization:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    
    
        http
          .authorizeRequests()
            .antMatchers("/", "/home").permitAll()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .anyRequest().authenticated()
            .and()
          .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
          .logout()
            .permitAll();
    }
    
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    
    
        auth
          .inMemoryAuthentication()
            .withUser("user").password("{noop}password").roles("USER")
            .and()
            .withUser("admin").password("{noop}password").roles("USER", "ADMIN");
    }
}

In the above code, we use authorizeRequeststhe method to configure the URL access rules. We allow all users to access the root path and /homethe path , and only ADMINusers with the role can access /adminthe path . For other URLs, authentication is required.

We configured form-based authentication using formLoginthe method . We specified the URL of the login page as /loginand allowed all users to access that URL. We also configured form-based logout using logoutthe method , allowing all users to log out.

Finally, we configure the user's authentication using configureGlobalthe method . Here, we have used memory-based authentication, specified two users userand admin, and set their passwords and roles.

sample code

Here is a complete sample code demonstrating how to use Spring Security for authentication and authorization in Spring Boot:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    
    
        http
          .authorizeRequests()
            .antMatchers("/", "/home").permitAll()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .anyRequest().authenticated()
            .and()
          .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
          .logout()
            .permitAll();
    }
    
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    
    
        auth
          .inMemoryAuthentication()
            .withUser("user").password("{noop}password").roles("USER")
            .and()
            .withUser("admin").password("{noop}password").roles("USER", "ADMIN");
    }
}

@Controller
public class HomeController {
    
    
    
    @GetMapping("/")
    public Stringhome() {
    
    
        return "home";
    }
    
    @GetMapping("/admin")
    public String admin() {
    
    
        return "admin";
    }
    
    @GetMapping("/login")
    public String login() {
    
    
        return "login";
    }
}

@SpringBootApplication
public class Application {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(Application.class, args);
    }

}

In the sample code above, we created HomeControllera controller called with three handler methods: home, adminand login. homeThe and adminmethods return a string representing the name of the view, while loginthe method returns the view name of the login page.

We also created a Spring Boot application class Applicationcalled and defined mainmethod in it to start the application.

In the sample code above, we used the Thymeleaf templating engine to render the view. We can also use other templating engines such as JSP or FreeMarker.

run sample code

To run the sample code above, we need to perform the following steps:

  1. Go to the root directory of the application on the command line.
  2. Execute mvn spring-boot:runthe command to start the application.
  3. Access in a browser http://localhost:8080/home, you can see homethe view .
  4. When accessing in a browser http://localhost:8080/admin, since the current user does not have ADMINa role , it will be redirected to the login page.
  5. Access in the browser http://localhost:8080/login, enter the user name and password, you can log in and access adminthe view .

in conclusion

In this article, we covered how to use Spring Security for authentication and authorization in Spring Boot. We added Spring Security dependencies, configured basic authentication and authorization, and provided sample code. With these steps, we can easily integrate Spring Security into our Spring Boot application to ensure application security.

Guess you like

Origin blog.csdn.net/it_xushixiong/article/details/131353257