springboot字段的权限控制


有些时候我们不想让一些权限不足的人看到一些敏感字段,因此我们可以使用注解+AOP+反射来实现将返回的对象中的敏感字段设置为null值。

1. 编写一个注解,在属性上使用,用来控制字段的权限

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ShowField {
    String value();
}

2. 编写一个切面,用来实现具体控制字段的逻辑

  • 下面的代码是将前端传入的字段和返回给前端的字段设置为null
@Aspect
public class FiledAspect {
    @Pointcut("execution(public * com.zkane.controller.*.*(..))")
    public void field() {}

    @Before("field()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        for (Object obj : args) {
            filterField(obj);
        }
    }

    @AfterReturning(returning = "obj", pointcut = "field()")
    public void doAfterReturning(Object obj) throws Throwable {
        filterField(obj);
    }

    private void filterField(Object obj) throws IllegalAccessException {
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field: fields) {
            field.setAccessible(true);
            ShowField showField = field.getAnnotation(ShowField.class);
            if (showField != null && showField.value().equals("Admin")) {
                field.set(obj, null);
            }
        }
    }

}

3. 在启动类将bean添加到ApplicationContext的容器中

@SpringBootApplication
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

	@Bean
	public FiledAspect filedAspect() {
		return new FiledAspect();
	}
}

4. 在需要进行权限控制的字段上添加注解

public class User {

    private String name;
    
    @ShowField("Admin")
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM