Spring Security is a Security framework that provides declarative secure access control solutions for Spring-based enterprise applications.
1. Core functionality
(1) certification
(2) the validation
1. Reference the framework directly
1. Add a dependency
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> < version > 2.4.4 < / version > < / dependency > < the dependency > < groupId > org. Springframework. Boot < / groupId > < artifactId > spring - the boot - starter ws-security < / artifactId > < version > 2.4.4 < / version > < / dependency >Copy the code
2. Create a startup class
@SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }}Copy the code
3. Create a Controller to receive requests
@RestController
@RequestMapping("/hello")
public class HelloSecurityController {
@RequestMapping("/world")
public String sayHello(){
return "Hello Spring Security";
}
}
Copy the code
4. Configure the user name and password in the Application configuration file
spring.security.user.name=
spring.security.user.password=123456
Copy the code
The browser initiates a request, and login verification is required to access the page
2. Use memory-based user information
Use: WebSecurityConfigurerAdapter control the content of the safety management Through inheritance WebSecurityConfigurerAdapter, rewrite the configure method to implement
There is no PasswordEncoder mapped for the id “null”
Springsecurity requires that passwords be encrypted
/ / the current class is a Configuration class @ the functions of Configuration / / said enabled SpringSecurity @ EnableWebSecurity public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {/ / configure the user information in the method, As the login data @ Override protected void the configure (AuthenticationManagerBuilder auth) throws the Exception {PasswordEncoder PE = passwordEncoder(); auth.inMemoryAuthentication() .withUser("yuan") .password(pe.encode("123456")).roles(); @bean public PasswordEncoder PasswordEncoder (){// Create the encryption algorithm implementation class return new BCryptPasswordEncoder(); }}Copy the code
3. Role-based identity authentication
The same user can have different roles
1. Set a role for the user
2. Add a method level enable annotation above the class
3. Add the role information to the handler method
// The current class is a Configuration class. @Configuration // Means to enable SpringSecurity. @enableWebSecurity // Enables method level authentication Said can use @ PreAuthorize @ PostAuthorize @ EnableGlobalMethodSecurity (prePostEnabled = true) public class MyWebSecurityConfig Extends WebSecurityConfigurerAdapter {/ / configure the user information in the method, as the login data / / defines two roles, normal,admin @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { PasswordEncoder pe = passwordEncoder(); auth.inMemoryAuthentication() .withUser("yuan") .password(pe.encode("123456")).roles("admin","normal"); } @bean public PasswordEncoder PasswordEncoder() {return new BCryptPasswordEncoder(); }}Copy the code
@RequestMapping("/helloUser") @Preauthorize (value = "hasAnyRole('admin','normal')") public String HelloCommomUser (){return "Hello user with the normal admin role "; } @requestMapping ("/helloAdmin") @preauthorize (value = "hasAnyRole('admin')") public String helloAdmin(){ return "hello admin"; }Copy the code
4. Jdbc-based user authentication
Gets the user’s identity information from the database
1. The representation class of the object User information is UserDetails, and the User class is the implementation class of the UserDetails interface
User class: an implementation of the UserDetails interface. The constructor takes three arguments: username, password, and authorities
Spring Security needs to be provided with a User object whose data comes from queries in the database
2. Implement the UserDetailsService interface, rewrite the UserDetails loadUserByUsername method, and obtain the user information of the database in the method
@Component("MyUserDetailService") public class MyUserDetailService implements UserDetailsService { @Autowired private UserInfoDao dao; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserInfo userInfo=null; if(username! =null){ userInfo=dao.findByUsername(username); if(userInfo! =null){ List<GrantedAuthority> list=new ArrayList<>(); GrantedAuthority authority=new SimpleGrantedAuthority("Role_"+userInfo.getRole()); list.add(authority); User user=new user (userinfo.getUsername (), userinfo.getPassword (),list); } } return null; }}Copy the code