注解使用
@Secured
判断是否具有角色,另外需要注意的是这里匹配的字符串需要添加前缀 ROLE_
。 类似hasAnyRole方法
开启注解功能
使用 @Secured
注解先要开启注解功能!@EnableGlobalMethodSecurity(securedEnabled = true)
@SpringBootApplication
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SpringSecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSecurityApplication.class, args);
}
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
Controller
@RestController
public class AnnotationController {
// 告诉SpringSecurity访问这个方法需要用户具有ROLE_admin或ROLE_manager角色才能访问成功
@Secured({"ROLE_admin", "ROLE_manager"})
@GetMapping("/testSecured")
public String testSecured(){
return "hello secured";
}
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
@PreAuthorize
@PreAuthorize:注解适合进入方法前的权限验证, @PreAuthorize 可以将登录用户的 roles/permissions 参数传到方法中。
开启注解功能
使用 @PreAuthorize
注解先要开启注解功能!@EnableGlobalMethodSecurity(prePostEnabled = true)
Controller
@MapperScan("org.hong.springsecurity01.mapper")
@EnableGlobalMethodSecurity(prePostEnabled = true)
@SpringBootApplication
public class Springsecurity01Application {
public static void main(String[] args) {
SpringApplication.run(Springsecurity01Application.class, args);
}
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
@PostAuthorize
@PostAuthorize
注解使用并不多,在方法执行后再进行权限验证,适合验证带有返回值的权限.
开启注解功能
使用 @PostAuthorize
注解先要开启注解功能!@EnableGlobalMethodSecurity(prePostEnabled = true)
Controller
// 使用与@PerAuthorize注解类似
@PostAuthorize("hasAuthority('admin')")
@GetMapping("/testPostAuthorize")
public String testPostAuthorize(){
System.out.println("update");
return "hello";
}
1
2
3
4
5
6
7
2
3
4
5
6
7
@PreFilte
@PreFilter: 进入控制器之前对数据进行过滤,Spring Security将移除使对应表达式的结果为false的元素。
@PreFilter("filterObject.length() > 2")
@GetMapping("/testPerFilter")
public String testPerFilter(@RequestParam ArrayList<String> list){
System.out.println(list.toString() + list.size());
return "hello testPerFilter";
}
1
2
3
4
5
6
2
3
4
5
6
只能对集合进行过滤,filterObject
代表集合中的项。
@PostFilter
@PostFilter :对方法返回的数据进行过滤,Spring Security将移除使对应表达式的结果为false的元素。
@PostFilter("filterObject.length() > 2")
@GetMapping("/testPostFilter")
public List<String> testPostFilter(){
List<String> list = new ArrayList<>();
list.add("abc");
list.add("ab");
return list;
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
只能对集合进行过滤,filterObject
代表集合中的项。
用户注销
logout.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h5>登录成功</h5>
<a href="/logout">登出</a>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
修改配置类
修改 configure(HttpSecurity http)
方法
// 退出配置
http.logout()
.logoutUrl("/logout") // 设置登出访问的url, 这个controller不需要我们定义
.logoutSuccessUrl("/login.html"); // 登出成功后的跳转页面
1
2
3
4
2
3
4
上次更新: 2024/03/29, 08:56:31