1.简介
Spring Security 是 Spring 家族的一个安全框架, 提供了全面的安全解决方案 , 对用户的身份进行认证, 以及验证每一个用户所具有的的权限, 根据用户的权限限制用户的操作。
Mybatis 是一款优秀的持久层框架 , 支持自定义 SQL 以及各种高级映射 , 与 JPA 的自动生成 SQL 相比, 它更加灵活, 本例使用 Mybatis 存储用户的身份和权限, 通过 Security 获取用户信息, 对用户的权限和操作进行管理。
2.实现代码
1.项目配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
username: root
password: roof
url: jdbc:mysql://localhost:3306/security?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&autoReconnect=true
# 配置前端Thymeleaf模板引擎
thymeleaf:
# 打包末尾无/
prefix: classpath:/templates/
check-template-location: true
suffix: .html
encoding: UTF-8
servlet:
content-type: text/html
mode: HTML5
# 禁止后实现前端热部署
cache: false
# 集成Mybatis
mybatis:
# Mybatis映射
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.hly.springBootSecurityMybatis.entity
# 端口设置
server:
port: 8081
2.Security 配置
@Configuration
@EnableWebSecurity//开启WebSecurity功能
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启方法上的保护
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
UserDetailsService userService(){
return new UserService();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
//从数据库中获取用户认证信息
auth.userDetailsService(userService());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
//不需要验证的资源
.antMatchers("/css/**", "/index").permitAll()
//需要验证,角色为Role
.antMatchers("/article/**").hasAnyRole("ADMIN","STUDENT","TEACHER")
.antMatchers("/admin/**").hasAnyRole("ADMIN","STUDENT","TEACHER")
.and()
//表单的登录地址和失败地址
.formLogin().loginPage("/login").failureForwardUrl("/loginError")
.and()
//异常处理界面
.exceptionHandling().accessDeniedPage("/401");
http.logout().logoutSuccessUrl("/");
}
}
3.controller 层
@Controller
public class ArticleController {
@Autowired
ArticleService articleService;
/**
* 查看文章列表
* @param model
* @return
*/
@RequestMapping("/article")
public ModelAndView articleList(Model model){
List<Article> list = articleService.getArticles();
model.addAttribute("articlesList",list);
return new ModelAndView("article/list","articleModel",model);
}
/**
* 给方法设置权限,没有ADMIN权限的用户不能删除文章
* @param id
* @param model
* @return
*/
@PreAuthorize("hasAnyAuthority('ROLE_ADMIN')")
@GetMapping(value = "/article/{id}/deletion")
public ModelAndView delete(@PathVariable("id")int id,Model model){
articleService.deleteArticle(id);
model.addAttribute("articlesList",articleService.getArticles());
return new ModelAndVi