04. 基于自定义Bean权限控制

基于自定义Bean权限控制

在Web 安全表达式中引用自定义Bean授权
1)定义自定义授权类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.po.service.impl;
 
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
 
/**
 * 自定义授权类
 */
@Component
public class MyAuthorizationService {
 
    /**
     * 检查用户是否有对应的访问权限
     *
     * @param authentication 登录用户
     * @param request 请求对象
     * @return
     */
 
    public boolean check(Authentication authentication, HttpServletRequest request) {
 
        User user = (User) authentication.getPrincipal();
        // 获取用户所有权限
        Collection<GrantedAuthority> authorities = user.getAuthorities();
        // 获取用户名
        String username = user.getUsername();
        // 如果用户名为admin,则不需要认证
        if (username.equalsIgnoreCase("admin")) {
            return true;
        } else {
            // 循环用户的权限, 判断是否有ROLE_ADMIN权限, 有返回true
            for (GrantedAuthority authority : authorities) {
                String role = authority.getAuthority();
                if ("ROLE_ADMIN".equals(role)) {
                    return true;
                }
            }
        }
        return false;
    }
}

配置类

1
2
3
//使用自定义Bean授权
http.authorizeRequests().antMatchers("/user/**").
access("@myAuthorizationService.check(authentication,request)");

用admin用户可以访问用户管理 用其它用户不可以访问用户管理

携带路径变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 检查用户是否有对应的访问权限
*
* @param authentication 登录用户
* @param request 请求对象
* @param id 参数ID
* @return
*/
public boolean check(Authentication authentication, HttpServletRequest request, Integer id) {
    if (id > 10) {
        return false;
    }
    return true;
}
 
//使用自定义Bean授权,并携带路径参数
http.authorizeRequests().antMatchers("/user/delete/{id}").
access("@myAuthorizationService.check(authentication,request,#id)"); 

 

 

posted @   __破  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示