Springboot如何基于实现访问权限限制
遇到⼀个需求是:要为⽤户设置不同的菜单、数据访问权限。对于⼀些特定类型的数据,有的⽤户可以看有的⽤户则不可以。⼀开始没有太多思路,后来⼀想是不是可以把"特定类型"这个参数通过@PathVariable注解加到路径上,这样就可以通过拦截后,校验此⽤户是否可以访问这个路径(类型)下的数据了。
话不多说,以下为具体实践
配置类
@Configuration
public class UserInterceptorConfig {
//为了保证IDbnetUserService提前实例化,能在userInterceptor使⽤
//ConditionalOnMissingBean可以保证只有⼀个IDbnetUserService的实例
@Bean
@ConditionalOnMissingBean(IDbnetUserService.class)
public IDbnetUserService dbnetUserService() {
return new DbnetUserServiceImpl();
}
//
@Bean(name = "userInterceptor")
public HandlerInterceptor userInterceptor(IDbnetUserService dbnetUserService) {
return new HandlerInterceptor() {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//url = RequestURI() 判断url是否可以有权限访问⽽返回true或者false
}
};
}
}
注册
//注册
@Bean
public WebMvcConfigurer registerInterceptor(@Qualifier("userInterceptor") HandlerInterceptor userInterceptor) {
return new WebMvcConfigurerAdapter() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//要拦截的路径
List<String> path = Path();
//要排除的路径
List<String> excludePath = ExcludePath();
registry.addInterceptor(userInterceptor).addPathPatterns(path.stream().toArray(String[]::new))
.excludePathPatterns(excludePath.stream().toArray(String[]::new));
}
};
}
配置要拦截的路径
@Component
@ConfigurationProperties(prefix = "dbnet.interceptor")
public class InterceptorProperties {
/**
* 需要拦截的接⼝通配
*/
private List<String> path = new ArrayList<>();
/**
* 需要忽略的接⼝通配
*/
private List<String> excludePath = new ArrayList<>();
public List<String> getPath() {
return path;
}
public void setPath(List<String> path) {
this.path = path;
}
public List<String> getExcludePath() {
return excludePath;
}
public void setExcludePath(List<String> excludePath) {
}
}
springboot和过滤器dbnet:
interceptor:
path: /dbnet/**,/datanet/**
excludePath: /dbnet/detail,/datanet/recommend,/datanet/count,/datanet/getKeys,/datenet/metadata/**以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。