Two important interfaces
- UserDetailsService interface
- Query database user name and password
- Create a class to inherit UsernamePasswordAuthenticationFilter and rewrite three methods
- Create a class to implement UserDetailsService, write a database query process, and return the User object, which is an object provided by the security framework
- PasswordEncode interface
- Data encryption interface, used to return the password encryption in the User object
Set login username and password
- Via configuration file
spring.security.user.name=fy
spring.security.user.password=fy123
- Through the configuration class
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String password = passwordEncoder.encode("123");
auth.inMemoryAuthentication().withUser("fyun").password(password).roles("admin");
}
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
- Custom write implementation class
- Create a configuration class and set which UserDetailsService implementation class to use
@Configuration public class MySecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Bean PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } }
- Write the implementation class, return the User object, the User object has the user name, password and operation authority
@Service("userDetailsService") public class MyUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { List<GrantedAuthority> role = AuthorityUtils.commaSeparatedStringToAuthorityList("role"); return new User("may",new BCryptPasswordEncoder().encode("my123"),role); } }
Query the database to complete user authentication
Integrate MybatisPlus to complete database operations
- Introduce related dependencies
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
- Create database and data table
CREATE TABLE USER(
id INTEGER AUTO_INCREMENT,
username VARCHAR(225) ,
PASSWORD VARCHAR(225),
PRIMARY KEY (id)
);
- Create User entity class
@Data
public class User {
private Integer id;
private String username;
private String password;
}
- Integrate MybatisPlus
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
- Write UserMapper interface
@Repository
public interface UserMapper extends BaseMapper<User> {
}
- write
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("username",username);
User user = userMapper.selectOne(wrapper);
if (user == null){
throw new UsernameNotFoundException("用户名不存在!");
}
List<GrantedAuthority> role = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
return new org.springframework.security.core.userdetails.User(user.getUsername(),new BCryptPasswordEncoder().encode(user.getPassword()),role);
}
}
- Configure data source
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://10.138.236.45/security?serverTimezone=GMT%2B8
Custom login page
- Override the configure method in the configuration class
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() //自定义自己编写的登录页面
.loginPage("/login.html") //登录页面设置
.loginProcessingUrl("/user/login") //登录访问路径
.defaultSuccessUrl("/test/index").permitAll() //登录成功之后的跳转路径
.and().authorizeRequests()
.antMatchers("/","/test/hello","/user/login").permitAll() //设置哪些路径可以直接访问
.anyRequest().authenticated()
.and().csrf().disable(); //关闭csrf防护
}
- Edit the login page
. The name attribute of the username and password must be "username" and "password"
<form action="/user/login" method="post">
用户名:<input type="text" name="username">
<br>
密码:<input type="text" name="password">
<br>
<input type="submit" value="login">
</form>