数据结构
首先是我的数据表设计
对我们的拦截器配置
WebConfigurer
@Configuration
public class WebConfigurer extends WebMvcConfigurationSupport {
@Autowired
private AuthorityInterceptorauthorityInterceptor;
@Bean
public MyInterceptormyInterceptor() {
return new MyInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authorityInterceptor);
registry.addInterceptor(myInterceptor()).addPathPatterns("/**")
.addPathPatterns("/admin/**")
.excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**","/config/**");
super.addInterceptors(registry);
}
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
@Bean
public ErrorPropertieserrorProperties() {
final ErrorProperties properties =new ErrorProperties();
properties.setIncludeStacktrace(IncludeStacktrace.ALWAYS);
return properties;
}
/**
* 使用@Bean注解注入第三方的解析框架(fastJson)
*
* @return
*/
@Bean
public HttpMessageConvertersfastJsonHttpMessageConverters() {
// 1、首先需要先定义一个convert转换消息对象
FastJsonHttpMessageConverter fastConverter =new FastJsonHttpMessageConverter();
// 2、添加fastJson的配置信息,比如:是否要格式化返回的json数据
FastJsonConfig fastJsonConfig =new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
// 3、在convert中添加配置信息
fastConverter.setFastJsonConfig(fastJsonConfig);
return new HttpMessageConverters(fastConverter);
}
@Bean(name ="multipartResolver")
public MultipartResolvermultipartResolver() {
CommonsMultipartResolver resolver =new CommonsMultipartResolver();
resolver.setDefaultEncoding("UTF-8");
//resolveLazily属性启用是为了推迟文件解析,以在在UploadAction中捕获文件大小异常
resolver.setResolveLazily(true);
resolver.setMaxInMemorySize(40960);
//上传文件大小 5M 5*1024*1024
resolver.setMaxUploadSize(5 *1024 *1024);
return resolver;
}
}
MyInterceptor
@Component
public class MyInterceptor implements HandlerInterceptor {
//private PermissionService permissionService;
private static final Loggerlogger = LoggerFactory.getLogger(MyInterceptor.class);
// @Autowired
// private HfAdminMapper hfAdminMapper;
// @Autowired
// private HelloTestService helloTestService;
// @Reference(registry = "dubboPermissionService", url = "dubbo://47.105.72.216:2181/com.hanfu.user.center.service.PermissionService")
// @Autowired
// Permission permissionService =new Permission();
@Autowired
PermissionServicepermissionService;
// Permission permissionService = new Permission();
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {// System.out.println(request.getSession());
// System.out.println(request.getParameter("name"));
// System.out.println(request.getSession().getAttribute("userId"));
// Example example = new Example(HfAuth.class);
// Example.Criteria criteria = example.createCriteria();
// criteria.andEqualTo("authKey",request.getParameter("userId"));
// List hfAuthList=hfAdminMapper.selectByExample(example);
// hfAuthList.get(0).getUserId();
// Permission permission = new Permission();
permissionService.test();
System.out.println(permissionService.test());
System.out.println(request);
System.out.println(response);
System.out.println(handler);
if (permissionService.hasPermission(request,response,handler)==true) {
return true;
}
response.sendError(HttpStatus.FORBIDDEN.value(), "无权限");
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
String methodName = method.getName();
logger.info("====拦截到了方法:{},在该方法执行之前执行====", methodName);
System.out.println(handler);
System.out.println(request);
// 返回 true 才会继续执行,返回 false 则取消当前请求
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)throws Exception {
logger.info("执行完方法之后进执行(Controller方法调用之后),但是此时还没进行视图渲染");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {
logger.info("整个请求都处理完咯,DispatcherServlet也渲染了对应的视图咯,此时我可以做一些清理的工作了");
}
}
此处注意的是要是使用了swagger须在拦截器将其路径放开
权限实体PermissionConstants
public class PermissionConstants {
//商品-----------------------------------------------------------------------------
/**
* 管理员-商品列表查询
*/
public static final StringADMIN_PRODUCT_LIST ="admin_product_list";
/**
* 管理员-删除商品
*/
public static final StringADMIN_PRODUCT_DELETE ="admin_product_delete";
/**
* 管理员-添加商品
*/
public static final StringADMIN_PRODUCT_INSERT ="admin_product_insert";
/**
* 管理员-修改商品
*/
public static final StringADMIN_PRODUCT_UPDATE ="admin_product_update";
//角色-----------------------------------------------------------------------------------------------------------
/**
* 管理员-查看角色列表
*/
public static final StringADMIN_ROLE_LIST ="admin_role_list";
/**
* 管理员-添加角色列表
*/
public static final StringADMIN_ROLE_INSERT ="admin_role_insert";
/**
* 管理员-修改角色列表
*/
public static final StringADMIN_ROLE_UPDATE ="admin_role_update";
/**
* 管理员-删除角色列表
*/
public static final StringADMIN_ROLE_DELETE ="admin_role_delete";
//商品类目管理---------------------------------------------------------------------------
/**
* 管理员-查看类目列表
*/
public static final StringADMIN_CATRGORY_LIST ="admin_category_list";
/**
* 管理员-增加类目列表
*/
public static final StringADMIN_CATRGORY_INSERT ="admin_category_insert";
/**
* 管理员-修改类目列表
*/
public static final StringADMIN_CATRGORY_UPDATE ="admin_category_update";
/**
* 管理员-删除类目列表
*/
public static final StringADMIN_CATRGORY_DELETE ="admin_category_delete";
//会员管理---------------------权限
/**
* 管理员-查看会员列表
*/
public static final StringADMIN_MEMBER_LIST ="admin_member_list";
/**
* 管理员-删除会员列表
*/
public static final StringADMIN_MEMBER_DELETE ="admin_member_delete";
/**
* 管理员-增加会员列表
*/
public static final StringADMIN_MEMBER_INSERT ="admin_member_insert";
/**
* 管理员-修改会员列表
*/
public static final StringADMIN_MEMBER_UPDATE ="admin_member_update";
//资产权限----------------------------------------------------------------
/**
* 管理员-查看资产列表
*/
public static final StringADMIN_PROPERTY_LIST ="admin_property_list";
/**
* 管理员-查看资产详情
*/
public static final StringADMIN_PROPERTY_DETAILS ="admin_property_details";
/**
* 管理员-提现
*/
public static final StringADMIN_PROPERTY_MONEY ="admin_property_money";
//活动权限---------------------------------------------------------------------------------------
/**
* 管理员-查看活动列表
*/
public static final StringADMIN_ACTIVITY_LIST ="admin_activity_list";
/**
* 管理员-查看活动详情
*/
public static final StringADMIN_ACTIVITY_DETAILS ="admin_activity_details";
/**
* 管理员-开启活动
*/
public static final StringADMIN_ACTIVITY_OPEN ="admin_activity_open";
/**
* 管理员-添加活动
*/
public static final StringADMIN_ACTIVITY_INSERT ="admin_activity_insert";
/**
* 管理员-编辑活动
*/
public static final StringADMIN_ACTIVITY_UPDATE ="admin_activity_update";
/**
* 管理员-删除活动
*/
public static final StringADMIN_ACTIVITY_DELETE ="admin_activity_delete";
//-------------------管理员权限-----------------------------------
/**
* 管理员-查看管理员
*/
public static final StringADMIN_ADMINISTRATOR_LIST ="admin_Administrator_list";
/**
* 管理员-编辑权限管理员
*/
public static final StringADMIN_ADMINISTRATOR_update ="admin_Administrator_update";
}
自定义注解,权限区别RequiredPermission
/**
* @author 皓月千里
* @description 与拦截器结合使用 验证权限
* @date 2019/1/7
* @since 1.0
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface RequiredPermission {
Stringvalue();
}
权限管理的逻辑实现PermissionImpl
@Service
//@org.apache.dubbo.config.annotation.Service(registry = "dubboPermissionService")
//@org.apache.dubbo.config.annotation.Service(registry = "dubboProductServer")
public class PermissionImpl implements PermissionService {
/**
* 皓月千里
*
* @param handler
* @return
*/
@Autowired
private UserRoleMapperuserRoleMapper;
@Autowired
private RoleJurisdictionMapperroleJurisdictionMapper;
@Autowired
private JurisdictionMapperjurisdictionMapper;
@Override
public boolean hasPermission(HttpServletRequest request, HttpServletResponse response, Object handler) {
System.out.println("进入了PermissionServiceImpl");
String userId="123";
Cookie[] cookies = request.getCookies();
if (cookies==null){
return false;
}
System.out.println(cookies);
for(Cookie cookie1 : cookies){
if (cookie1.getName().equals("autologin")) {
System.out.println("name:" + cookie1.getName() +",value:" + cookie1.getValue());
userId=cookie1.getValue();
}
}
System.out.println(userId);
Example example =new Example(UserRole.class);
Example.Criteria criteria = example.createCriteria();
criteria.andEqualTo("userId",userId);
List userRoleList=userRoleMapper.selectByExample(example);
if (userRoleList.size()==0){
return false;
}
Integer roleId=userRoleList.get(0).getRoleId();
System.out.println(roleId);
//权限角色
Example example1 =new Example(RoleJurisdiction.class);
Example.Criteria criteria1 = example1.createCriteria();
criteria1.andEqualTo("roleId",roleId);
List roleJurisdictionList=roleJurisdictionMapper.selectByExample(example1);
if (handlerinstanceof HandlerMethod) {
String permissionSet ="admin_product_list1";
HandlerMethod handlerMethod = (HandlerMethod) handler;
// 获取方法上的注解
RequiredPermission requiredPermission = handlerMethod.getMethod().getAnnotation(RequiredPermission.class);
System.out.println(requiredPermission);
// 如果方法上的注解为空 则获取类的注解
if (requiredPermission ==null) {
requiredPermission = handlerMethod.getMethod().getDeclaringClass().getAnnotation(RequiredPermission.class);
System.out.println(requiredPermission);
}
if (requiredPermission ==null){
System.out.println(true);
return true;
}
// 如果标记了注解,则判断权限
if (requiredPermission !=null && StringUtils.isNotBlank(requiredPermission.value())) {
// redis或数据库 中获取该用户的权限信息 并判断是否有权限
System.out.println(roleJurisdictionList);
if (roleJurisdictionList.size()==0){
System.out.println(false);
return false;
}
for (int i=0;i
int JurisdictionId= roleJurisdictionList.get(i).getJurisdictionId();
String Jurisdiction=jurisdictionMapper.selectByPrimaryKey(JurisdictionId).getAccessCode();
System.out.println(Jurisdiction+"jjjjbbbb");
permissionSet=Jurisdiction;
if (requiredPermission.value().equals(permissionSet)){
System.out.println("1231312421341234214124");
return true;
}
}
return false;
}
}
return true;
}
@Override
public int test() {
System.out.println(11111);
return 0;
}
}
验证登录
我这里是将用户登录的id存入Cookie cookie =new Cookie("autologin", authKey);
cookie.setPath("/");
response.addCookie(cookie);
每次调用的时候去cookie取,关闭浏览器消失。
使用时在接口上方或者方法上方加@RequiredPermission(PermissionConstants.ADMIN_PRODUCT_LIST)
其中的主要实现逻辑:通过拦截器拦截请求,拦截器将登录接口放开,将验证放入cookie,每次请求接口的时候拦截器取登录验证的信息比如user_id,如无拦截,有根据userid查询对应角色权限,与方法或者接口上注解的参数对比。
Java小白欢迎大家提出意见