阳光沙滩博客系统-接口权限控制

前面我们都是通过判断当前用户的角色来判断权限的

接下来我们通过注解的形式

# 开启认证

@EnableGlobalMethodSecurity(prePostEnabled = true)
1

在applicatoin或者在我们的securityConfig上配置。

# 创建一个PermissionCheckService

@Service("permission")
public class PermissionCheckService {

    @Autowired
    private IUserService userService;

    public boolean adminPermission() {
        // 获取到当前权限所有的角色,进行角色对比即可确定权限
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        //如果token返回false
        String token = CookieUtils.getCookie(request, Constants.User.COOKIE_TOKE_KEY);
        if (TextUtils.isEmpty(token)) {
            return false;
        }
        SobUser sobUser = userService.checkSobUser(request, response);
        if (sobUser == null || TextUtils.isEmpty(sobUser.getRoles())) {
            return false;
        }
        if (Constants.User.ROLE_ADMIN.equals(sobUser.getRoles())) {
            return true;
        }
        return false;
    }

}
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

# 权限控制

@PreAuthorize("@permission.adminPermission()")
@GetMapping("/list")
public ResponseResult listUsers(HttpServletRequest request,
                                HttpServletResponse response,
                                @RequestParam("page") int page, @RequestParam("size") int size) {
    return userService.listUsers(request,
                                 response, page, size);
}
1
2
3
4
5
6
7
8

# 403无权限访问处理

添加一个配置

@Configuration
public class ErrorPageConfig implements ErrorPageRegistrar {
    @Override
    public void registerErrorPages(ErrorPageRegistry registry) {
        registry.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN, "/403"));
    }
}
1
2
3
4
5
6
7

提供一个403的controller-->从code转成Json

@GetMapping("/403")
@ResponseBody
public ResponseResult page403() {
    ResponseResult failed = new ResponseResult(ResponseState.ACCOUNT_FORBID);
    return failed;
}
1
2
3
4
5
6
上次更新: 2022/03/28, 23:04:38