foreword
"Author's Homepage" : Sprite Youbai Bubbles
"Personal Website" : Sprite's personal website
"Recommendation Column" :
★ Java one-stop service ★
★ Front-end cool code sharing
★ ★ uniapp-from construction to promotion ★
★ From 0 to hero, Vue's road to god ★
★ Solving algorithm, one column is enough ★
★ Let's talk about architecture from 0 ★
★ The Exquisite Way of Data Circulation ★
★ The Road to Advanced Backend ★
Article directory
Here is the text after adding the # sign before each heading:
✍1. Introduction
✌ Background introduction: the importance of network security
The importance of cybersecurity cannot be underestimated. As we rely more and more on the internet and digital technology, the issue of cybersecurity becomes even more critical. Here are a few important aspects of cybersecurity:
Preventing data breaches: Cyber security ensures that our personal information, sensitive data and business secrets do not fall into unauthorized hands. This includes bank account information, social media accounts, medical records, and more.
Prevent hacker attacks: Hackers can invade network systems in various ways to steal information, damage systems or extort money. Cyber security measures help prevent these attacks and protect our computers, mobile devices and internet connections.
Maintain enterprise security: For enterprises, network security is of paramount importance. Protect your company's data and confidential information, prevent competitors or malicious actors from obtaining sensitive information, and ensure business continuity and reputation.
Protecting Personal Privacy: In the digital age, our personal privacy is under threat. Online security helps us protect our personal identities and privacy and avoid becoming victims of identity theft, online fraud or online harassment.
Preventing Cybercrime: Cybersecurity is critical to combating cybercrime. Cybercrime includes telecom fraud, phishing, malware distribution, and more. By strengthening cybersecurity, the incidence of these crimes can be reduced and the safety and order of society can be maintained.
✌ Introduction to Spring Security: What is Spring Security, its functions and advantages
Spring Security is a framework for implementing authentication and authorization in Java applications. It secures applications to prevent unauthorized access and ensures that only authenticated users can perform certain actions.
The main role of Spring Security is to provide comprehensive security solutions, including user authentication, authorization, session management, and password encryption. It can be easily integrated into Spring applications and configured and customized to meet various security needs.
Following are few advantages of Spring Security:
Unified security management and control: Spring Security provides a comprehensive security management framework, allowing developers to centrally manage the security of applications without having to repeatedly write security-related code.
Flexible authentication and authorization mechanisms: Spring Security supports multiple authentication methods, such as form-based authentication, HTTP Basic and Digest authentication, LDAP authentication, etc. It also provides a fine-grained authorization mechanism, which can define permission rules through annotations or configuration.
Security scalability: Spring Security has good scalability and can be seamlessly integrated with other frameworks and technologies, such as Spring Framework, OAuth, OpenID, etc. This allows developers to choose an appropriate security solution based on project needs.
Built-in defenses: Spring Security provides built-in defenses against common security threats, such as cross-site request forgery (CSRF) protection, clickjacking protection, session management, and more. These functions can effectively improve the security of the application.
✍2. Basic concepts of Spring Security
Spring Security is a Java-based authentication and access control framework for securing web applications and services. It provides a powerful set of security features to help developers implement various authentication and authorization schemes in their applications.
✌Authentication: Verify user identity
Authentication is the process of confirming the identity of a user . When a user tries to log in to the system, Spring Security verifies whether the credentials provided by the user are valid, and builds an object representing the user's identity based on the verification result, called an Authentication object.
code demo
When using Spring Security for authentication, the authentication process can be understood through the following code snippet:
1. Create a custom UserDetailsService
implementation of to load user information:
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User not found with username: " + username);
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
getAuthorities(user.getRoles()));
}
private Collection<? extends GrantedAuthority> getAuthorities(Set<Role> roles) {
return roles.stream()
.map(role -> new SimpleGrantedAuthority(role.getName()))
.collect(Collectors.toList());
}
}
2. Configure Spring Security to use the above UserDetailsService
implementation:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
// 密码加密器
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated()
.and()
.formLogin().permitAll()
.and()
.logout().permitAll();
}
}
3. Handle the login request in the controller:
@Controller
public class LoginController {
@GetMapping("/login")
public String login() {
return "login";
}
@GetMapping("/")
public String home() {
return "home";
}
}
The above code demonstrates a basic Spring
Security authentication process. When a user tries to access a protected resource, they are redirected to a login page (/login
). After the user enters a username and password, Spring
Security willUserDetailsService
load the user information via and authenticate with the provided credentials. If authentication is successful, a object is created
Authentication
representing the user identity and allowing the user to access protected resources.
✌Authorization: Grant user access
Authorization is the process of determining whether a user has permission to perform an action or access a resource . Spring Security provides a rich authorization mechanism, including authorization methods based on roles (Role) and permissions (Permission).
code demo
When it comes to authorization, Spring Security provides several common authorization methods. Below are some code snippets to help understand these authorization mechanisms.
1. Role-based authorization:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated()
.and()
.formLogin();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER")
.and()
.withUser("admin").password("{noop}password").roles("ADMIN");
}
}
In the above example, we used role-based authorization. With
hasRole()
the andhasAnyRole()
methods, we can specify which roles have access. InconfigureGlobal()
the method, we use a simple in-memory authentication with two users with different roles.
2. Permission-based authorization:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasAuthority("ADMIN")
.antMatchers("/user/**").hasAnyAuthority("USER", "ADMIN")
.anyRequest().authenticated()
.and()
.formLogin();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").authorities("USER")
.and()
.withUser("admin").password("{noop}password").authorities("ADMIN");
}
}
In the example above, we used permission-based authorization. With
hasAuthority()
the andhasAnyAuthority()
methods, we can specify which permissions have access. InconfigureGlobal()
the method, we used the same in-memory authentication, but this time we assigned different permissions.
✌Security Context: Save authenticated user information
User Details (User Details): User Details is an interface representing user information in Spring Security , usually implemented by developers to provide custom user information. It contains the user's username, password, roles, and other attributes.
code demo
The following is to customize user details (User Details) and save authenticated user information in the security context (Security Context).
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
public class CustomUserDetails implements UserDetails {
private String username;
private String password;
private Collection<? extends GrantedAuthority> authorities;
public CustomUserDetails(String username, String password, Collection<? extends GrantedAuthority> authorities) {
this.username = username;
this.password = password;
this.authorities = authorities;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
// 下面的方法可以根据实际需求进行实现
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
In the above code,
CustomUserDetails
the class implementsUserDetails
the interface and provides the necessary methods to obtain attributes such as username, password, and user roles. This class is a developer-defined implementation of user details.
Once you have verified the user's credentials during the authentication process, you can create CustomUserDetails
the instance and place it in the security context:
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
public class AuthenticationService {
public void authenticateUser(String username, String password) {
// 通过验证用户名和密码
// 创建用户详情
UserDetails userDetails = new CustomUserDetails(username, password, authorities);
// 创建认证对象
Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, password, authorities);
// 将认证对象放入安全上下文
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
In the code above,
authenticateUser
the method creates anCustomUserDetails
instance and uses that instance to create a
UsernamePasswordAuthenticationToken
object. It then places the authentication object into the security context so that authenticated user information can be accessed later.
✌Filter Chain: the process of processing requests
Filter Chain (Filter Chain): The filter chain is one of the core components of Spring Security and is responsible for processing the security of requests. It consists of multiple filters, each responsible for performing specific security operations such as authentication, authorization checks, etc.
Below is a basic Spring Security filter chain configuration
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.logout();
}
}
In the example above,
SecurityConfig
the class inherits fromWebSecurityConfigurerAdapter
, which is a convenient base class for configuring Spring
Security.
configure()
method for the configurationHttpSecurity
object, which defines the behavior of the filter chain. In this example, the filter chain does the following:
authorizeRequests()
: Configure request authorization rules..antMatchers("/public/**").permitAll()
: Allow all users to access/public/
URLs starting with ..anyRequest().authenticated()
: For all other requests, require the user to authenticate..formLogin()
: Enables forms-based authentication..logout()
: Enable the logout function.
✍Summary
Spring Security is a powerful Java framework for implementing Authentication and Authorization functions in applications. It provides a set of fine-grained security controls to help protect applications from malicious attacks and unauthorized access.
In the next article, we will describe Spring Security configuration issues in detail