在这之前所需要的依赖以及其他配置
maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
其他配置
server.port=8081
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
index页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
hello security
</body>
</html>
控制器
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping("/index")
public String index(){
return "index";
}
}
方式一:通过配置文件配置用户和密码
#方式一:配置配置文件
spring.security.user.name=zhangsan
spring.security.user.password=zhangsan
运行效果:
方式二:通过配置类继承WebSecurityConfigurerAdapter重写其中configure(WebSecurity web)方法
注意:在配置密码时要加密需要使用PasswordEncoder来对密码进行加密,否则会报错,错误如下
java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
配置类:
/**
* 方式二:通过配置类继承WebSecurityConfigurerAdapter重写其中configure(WebSecurity web)方法
* 注意:在配置密码时要加密需要使用PasswordEncoder来对密码进行加密,否则会报错,错误如下
* java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
public void configure(AuthenticationManagerBuilder auth) throws Exception {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String passw = passwordEncoder.encode("123");
auth.inMemoryAuthentication().withUser("lisi").password("123").roles("admin");
//也可通过jdbc获取用户密码
//auth.jdbcAuthentication()
}
@Bean
public PasswordEncoder encoder(){
return new BCryptPasswordEncoder();
}
}
运行结果
方式三:通过UserDetailsService自定义实现类设置(比较经常使用)
**第一步:创建配置类,配置使用那个UserDetailsService **
/**
* 方式三:通过UserDetailsService自定义实现类设置
*/
@Configuration
public class SecurityConfigTest extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(encoder());
}
@Bean
public PasswordEncoder encoder(){
return new BCryptPasswordEncoder();
}
}
第二步:实现UserDetailsService类
@Service("userDetailsService")
public class MyUserDetailsService implements Use![在这里插入图片描述](https://img-blog.csdnimg.cn/20210113095204779.gif#pic_center)
rDetailsService {
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
//权限不能为空,一般是从数据库中读取
return new User("zhaoliu",new BCryptPasswordEncoder().encode("abcde"),auths);
}
}
运行效果: