當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
[SpringSecurity]web权限方案_用户授权_注解使用
生活随笔
收集整理的這篇文章主要介紹了
[SpringSecurity]web权限方案_用户授权_注解使用
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
注解使用
@Secured
判斷用戶是否具有角色,可以訪問方法,另外需要注意的是這里匹配的字符串需要添加前綴“ROLE_“。
使用注解先要開啟注解功能!
啟動類(配置類)開啟注解
- @EnableGlobalMethodSecurity(securedEnable = true)
在controller的方法上面使用注解,設置角色
@RestController @RequestMapping("/test") public class TestController {@GetMapping("hello")public String hello(){return "hello security";}@GetMapping("index")public String index(){return "hello index";}@GetMapping("update")@Secured({"ROLE_sale","ROLE_manager"})public String update(){return "hello update";} }userDetailsService設置用戶角色
測試
@PreAuthorize
適合進入方法前的權限驗證
啟動類開啟注解
在controller的方法上面添加注解
userDetailsService設置用戶角色
測試
@PostAuthorize
在方法執(zhí)行后再進行權限驗證,適合驗證帶有返回值的權限.
開啟注解
- @EnableGlobalMethodSecurity(prePostEnabled = true)
在controller的方法上面添加注解
測試
可以看到?jīng)]有訪問權限,但是控制臺還是輸出了update…,說明在方法執(zhí)行后再進行權限驗證!
@PostFilter
- 方法返回數(shù)據(jù)進行過濾
@PostFilter :權限驗證之后對數(shù)據(jù)進行過濾 留下用戶名是 admin1 的數(shù)據(jù)
表達式中的 filterObject 引用的是方法返回值 List 中的某一個元素
測試
package com.atguigu.securitydemo1.entity;import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor;@Data @AllArgsConstructor @NoArgsConstructor public class Users {private Integer id;private String username;private String password;} @GetMapping("getAll")@PostAuthorize("hasAnyAuthority('admins')")@PostFilter("filterObject.username == 'admin1'")public List<Users> getAllUser(){ArrayList<Users> list = new ArrayList<>();list.add(new Users(11,"admin1","6666"));list.add(new Users(21,"admin2","888"));System.out.println(list);return list;}@PreFilter
- 傳入方法數(shù)據(jù)進行過濾
@PreFilter: 進入控制器之前對數(shù)據(jù)進行過濾
總結
以上是生活随笔為你收集整理的[SpringSecurity]web权限方案_用户授权_注解使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 阿迪达斯三叶草和三条有什么区别(三叶草凭
- 下一篇: 网络小说如何打造非常惊艳的开篇如何写好小