您当前的位置: 首页 >  spring

wu@55555

暂无认证

  • 3浏览

    0关注

    201博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Springboot实现自定义注解权限校验

wu@55555 发布时间:2020-11-04 14:37:58 ,浏览量:3

Springboot实现自定义注解权限校验
  • 自定义注解类
  • 定义拦截器
  • 注册拦截器
  • 注解使用示例
    • controller层
    • js层

自定义注解类
/**
 * @author whx
 * 权限
 */
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FunctionPermission {

     int functionId() default 0;
}

@Documented 用来标注生成javadoc的时候是否会被记录 @Target(ElementType.METHOD) 表示注解的作用目标是方法 @Retention(RetentionPolicy.RUNTIME) 表示注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在

定义拦截器
/**
 * @author whx
 * 权限检验
 **/
@Component
public class FunctionPermissionInterceptor implements HandlerInterceptor {

    protected Logger LOG = LoggerFactory.getLogger(getClass());

    // 是否允许测试用户  开启后不校验权限
    @Value("${icdc.enableTestUser: false}")
    boolean enableTestUser;
    
    @Autowired
    LogonUserService logonUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            FunctionPermission function = method.getAnnotation(FunctionPermission.class);
            if (function != null) {
                int functionId = function.functionId();//获取方法ID
                if(functionId != 0) {
                    // 获取当前登录用户,通过session获取,具体实现略
                    LogonUserInfo logonInfo = logonUserService.getLogonUserInfo(request);
                    if (logonInfo == null) {
                      return enableTestUser;
                    }
                    // 根据用户ID与功能ID查询权限
                    
                    // 如果有权限则返回true 这里省略该具体实现
                    String userName = logonInfo.getLogonUserName();
                    throw new Exception(String.format("用户[%s]无权访问功能[%s]", userName, functionId));
                }
            }
            return true;
        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    }
}
注册拦截器
/**
 * @author whx
 **/
@Configuration
public class PermissionConfig implements WebMvcConfigurer {

    @Autowired
    private FunctionPermissionInterceptor permissionInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(permissionInterceptor).addPathPatterns("/**");
    }
}
注解使用示例 controller层
    @FunctionPermission(functionId = -1)
	@PostMapping("/users2")
	@LoginRequired
	public ResultData listCustomerUserAccounts2(@RequestBody UserAccount userAccount) {
		ResultData res = new ResultData();
		try{
			List result = userService.selectName();
			res.setState(1);
			res.setDataList(result);
		}catch (Exception e){
			res.setState(0);
			res.setMessage("获取失败:"+e.toString());
		}
		return res;
	}
js层
function loadPage() {
    var data = {userName:"test"};
    $.ajax({
        type: "POST",                       // 方法类型
        url: httpUrl + "/users2",          // url
        async: false,                       // 同步
        data: JSON.stringify(data),
        dataType: "json",
        // contentType: 'application/x-www-form-urlencoded',
        contentType: 'application/json;charset=utf-8',
        success: function (result) {
            console.log("查询结果", result);
        },
        error: function (result) {
            if(result.responseJSON !=null){
                alert(result.responseJSON.message);
            }
        }
    });
}
关注
打赏
1664985904
查看更多评论
立即登录/注册

微信扫码登录

0.0440s