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.
Add Spring Security dependency
First, we need to add the Spring Security dependency to pom.xml
the file :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
In the above dependencies, we added spring-boot-starter-security
the 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 SecurityConfig
called and annotate @EnableWebSecurity
it. This annotation enables Spring Security and automatically configures basic web security.
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
}
Next, we can override configure
the 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 authorizeRequests
the method to configure the URL access rules. We allow all users to access the root path and /home
the path , and only ADMIN
users with the role can access /admin
the path . For other URLs, authentication is required.
We configured form-based authentication using formLogin
the method . We specified the URL of the login page as /login
and allowed all users to access that URL. We also configured form-based logout using logout
the method , allowing all users to log out.
Finally, we configure the user's authentication using configureGlobal
the method . Here, we have used memory-based authentication, specified two users user
and 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 HomeController
a controller called with three handler methods: home
, admin
and login
. home
The and admin
methods return a string representing the name of the view, while login
the method returns the view name of the login page.
We also created a Spring Boot application class Application
called and defined main
method 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:
- Go to the root directory of the application on the command line.
- Execute
mvn spring-boot:run
the command to start the application. - Access in a browser
http://localhost:8080/home
, you can seehome
the view . - When accessing in a browser
http://localhost:8080/admin
, since the current user does not haveADMIN
a role , it will be redirected to the login page. - Access in the browser
http://localhost:8080/login
, enter the user name and password, you can log in and accessadmin
the 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.