RBAC是各类系统中应用最广泛的访问控制机制。使用RBAC时,一个比较复杂的问题是维护数据库中的规则列表。本文使用Java注解实现了规则的自动提取,程序员只需要在需要权限控制的方法上方用RBAC注解说明规则名,规则url和能使用该方法的角色名即可。
RBAC表结构
一、RBAC注解
package annotation.rbac;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD})
public @interface Rbac {
String url();
String[] role();
String name();
}
二、角色定义
package annotation.rbac;
public class Roles {
public static final String ADMIN="admin";
public static final String MANAGER="manager";
public static final String TEACHER="teacher";
public static final String STUDENT="student";
}
三、在控制器上使用注解
package annotation.rbac;
public class UserController {
@Rbac(name="添加用户",url="/admin/adduser",role={Roles.ADMIN,Roles.MANAGER})
public String addUser(String username,String password){
return "success";
}
@Rbac(name="用户注销",url="/logout",role={Roles.ADMIN,Roles.MANAGER,Roles.STUDENT,Roles.TEACHER})
public String logout()
{
return "success";
}
@Rbac(name="成绩查询",url="/query",role=Roles.STUDENT)
public String query(){
return "success";
}
@Rbac(name="成绩录入",url="/insert",role=Roles.TEACHER)
public String insert(){
return "success";
}
}
四、注解解析器,用于提取RBAC规则。进行修改之后可对所有控制器进行分析并生成数据插入数据库。
package annotation.rbac;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Set;
public class RbacParser {
public static void main(String[] args) {
try {
HashMap<String,String> roleTable=new HashMap<>();
int ruleId=1;
Class c = Class.forName("annotation.rbac.UserController");
Method[] methods=c.getMethods();
for(Method m:methods){
Annotation[] annotations=m.getDeclaredAnnotations();
for(Annotation annotation:annotations){
if(annotation instanceof Rbac){
Rbac rbacAnnotation=(Rbac) annotation;
String url=rbacAnnotation.url();
String name=rbacAnnotation.name();
String[] methodRoles=rbacAnnotation.role();
//后面需要将这条语句转换为SQL插入到数据库表rules
System.out.printf("rule_id:%d name:%s url:%s\n",ruleId,name,url);
//将角色具有权限的rule的编号拼接成逗号分隔的字符串,存放到HashMap
for(String role:methodRoles){
if(roleTable.containsKey(role)){
String s=roleTable.get(role);
roleTable.put(role, s+","+ruleId);
}else{
roleTable.put(role, String.valueOf(ruleId));
}
}
ruleId++;
}
}
}
//后面需要将下面的输出语句转换为SQL插入到数据库表Roles
Set<String> roleNames = roleTable.keySet();
for(String roleName:roleNames){
System.out.printf("role_name:%s rules:%s\n",roleName,roleTable.get(roleName));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}