安全性中的Spring AOP –通过方面控制UI组件的创建

以下文章将显示在我参与的一个项目中,我们如何使用Spring的AOP来介绍一些与安全性相关的功能。 这样的概念是为了使用户能够看到一些UI组件,他需要具有一定级别的安全特权。 如果不满足该要求,则不会显示UIComponent。 让我们看一下项目结构:

然后还有aopApplicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"><aop:aspectj-autoproxy /><context:annotation-config /><context:component-scan base-package="pl.grzejszczak.marcin.aop"><context:exclude-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/></context:component-scan><bean class="pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor" factory-method="aspectOf"/> </beans>

现在,让我们看一下Spring应用程序上下文中最有趣的几行。 首先,我们拥有所有必需的模式-我认为不需要对此进行更深入的解释。 然后我们有:

<aop:aspectj-autoproxy/>

启用@AspectJ支持。 接下来是

<context:annotation-config />
<context:component-scan base-package="pl.grzejszczak.marcin.aop"><context:exclude-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/>
</context:component-scan>

首先,我们通过注释打开Spring配置。 然后,我们故意排除了由Spring本身将其初始化为Bean的方面。 为什么? 因为…

<bean class="pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor" factory-method="aspectOf"/>

我们希望自己创建方面,并提供factory-method =” aspectOf”。 这样,我们的方面将包含在我们的bean的自动装配过程中-因此,所有带有@Autowired注释的字段都将注入bean。 现在让我们继续执行代码:

UserServiceImpl.java

package pl.grzejszczak.marcin.aop.service;import org.springframework.stereotype.Service;import pl.grzejszczak.marcin.aop.type.Role;
import pl.grzejszczak.marcin.aop.user.UserHolder;@Service
public class UserServiceImpl implements UserService {private UserHolder userHolder;@Overridepublic UserHolder getCurrentUser() {return userHolder;}@Overridepublic void setCurrentUser(UserHolder userHolder) {this.userHolder = userHolder;}@Overridepublic Role getUserRole() {if (userHolder == null) {return null;}return userHolder.getUserRole();}
}

UserServiceImpl类正在模仿一种服务,该服务将从数据库或当前应用程序上下文中获取当前用户信息。

UserHolder.java

package pl.grzejszczak.marcin.aop.user;import pl.grzejszczak.marcin.aop.type.Role;public class UserHolder {private Role userRole;public UserHolder(Role userRole) {this.userRole = userRole;}public Role getUserRole() {return userRole;}public void setUserRole(Role userRole) {this.userRole = userRole;}
}

这是一个简单的持有人类,其中包含有关当前用户角色的信息。

角色.java

package pl.grzejszczak.marcin.aop.type;public enum Role {ADMIN("ADM"), WRITER("WRT"), GUEST("GST");private String name;private Role(String name) {this.name = name;}public static Role getRoleByName(String name) {for (Role role : Role.values()) {if (role.name.equals(name)) {return role;}}throw new IllegalArgumentException("No such role exists [" + name + "]");}public String getName() {return this.name;}@Overridepublic String toString() {return name;}
}

角色是一个枚举,它为管理员作家来宾定义了一个角色。

UIComponent.java

package pl.grzejszczak.marcin.aop.ui;public abstract class UIComponent {protected String componentName;protected String getComponentName() {return componentName;}}

一些UI组件的具体实现的抽象。

SomeComponentForAdminAndGuest.java

package pl.grzejszczak.marcin.aop.ui;import pl.grzejszczak.marcin.aop.annotation.SecurityAnnotation;
import pl.grzejszczak.marcin.aop.type.Role;@SecurityAnnotation(allowedRole = { Role.ADMIN, Role.GUEST })
public class SomeComponentForAdminAndGuest extends UIComponent {public SomeComponentForAdminAndGuest() {this.componentName = "SomeComponentForAdmin";}public static UIComponent getComponent() {return new SomeComponentForAdminAndGuest();}
}

此组件是UI组件扩展的示例,只有拥有AdminGuest角色的用户才能看到。

SecurityAnnotation.java

package pl.grzejszczak.marcin.aop.annotation;import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;import pl.grzejszczak.marcin.aop.type.Role;@Retention(RetentionPolicy.RUNTIME)
public @interface SecurityAnnotation {Role[] allowedRole();
}

定义可以创建此组件的角色的注释。

UIFactoryImpl.java

package pl.grzejszczak.marcin.aop.ui;import org.apache.commons.lang.NullArgumentException;
import org.springframework.stereotype.Component;@Component
public class UIFactoryImpl implements UIFactory {@Overridepublic UIComponent createComponent(Class<? extends UIComponent> componentClass) throws Exception {if (componentClass == null) {throw new NullArgumentException("Provide class for the component");}return (UIComponent) Class.forName(componentClass.getName()).newInstance();}
}

给定扩展UIComponent的对象类的工厂类将返回给定UIComponent的新实例。

SecurityInterceptor.java

package pl.grzejszczak.marcin.aop.interceptor;import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.util.Arrays;
import java.util.List;import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;import pl.grzejszczak.marcin.aop.annotation.SecurityAnnotation;
import pl.grzejszczak.marcin.aop.service.UserService;
import pl.grzejszczak.marcin.aop.type.Role;
import pl.grzejszczak.marcin.aop.ui.UIComponent;@Aspect
public class SecurityInterceptor {private static final Logger LOGGER = LoggerFactory.getLogger(SecurityInterceptor.class);public SecurityInterceptor() {LOGGER.debug("Security Interceptor created");}@Autowiredprivate UserService userService;@Pointcut("execution(pl.grzejszczak.marcin.aop.ui.UIComponent pl.grzejszczak.marcin.aop.ui.UIFactory.createComponent(..))")private void getComponent(ProceedingJoinPoint thisJoinPoint) {}@Around("getComponent(thisJoinPoint)")public UIComponent checkSecurity(ProceedingJoinPoint thisJoinPoint) throws Throwable {LOGGER.info("Intercepting creation of a component");Object[] arguments = thisJoinPoint.getArgs();if (arguments.length == 0) {return null;}Annotation annotation = checkTheAnnotation(arguments);boolean securityAnnotationPresent = (annotation != null);if (securityAnnotationPresent) {boolean userHasRole = verifyRole(annotation);if (!userHasRole) {LOGGER.info("Current user doesn't have permission to have this component created");return null;}}LOGGER.info("Current user has required permissions for creating a component");return (UIComponent) thisJoinPoint.proceed();}/*** Basing on the method's argument check if the class is annotataed with* {@link SecurityAnnotation}* * @param arguments* @return*/private Annotation checkTheAnnotation(Object[] arguments) {Object concreteClass = arguments[0];LOGGER.info("Argument's class - [{}]", new Object[] { arguments });AnnotatedElement annotatedElement = (AnnotatedElement) concreteClass;Annotation annotation = annotatedElement.getAnnotation(SecurityAnnotation.class);LOGGER.info("Annotation present - [{}]", new Object[] { annotation });return annotation;}/*** The function verifies if the current user has sufficient privilages to* have the component built* * @param annotation* @return*/private boolean verifyRole(Annotation annotation) {LOGGER.info("Security annotation is present so checking if the user can use it");SecurityAnnotation annotationRule = (SecurityAnnotation) annotation;List<Role> requiredRolesList = Arrays.asList(annotationRule.allowedRole());Role userRole = userService.getUserRole();return requiredRolesList.contains(userRole);}
}

这是在执行函数createComponent的切入点处定义的方面
UIFactory接口。 在“ 环绕” 建议中,存在一种逻辑,该逻辑首先检查将什么样的参数传递给方法createComponent(例如SomeComponentForAdminAndGuest.class)。 接下来,检查此类是否用SecurityAnnotation进行注释,如果是,它将检查创建组件所需的角色类型。 然后,它检查当前用户(从UserService到UserHolder的Roles)是否具有呈现组件所需的角色。 如果是这样的话 调用thisJoinPoint.proceed(),实际上返回扩展UIComponent的类的对象。 现在让我们对其进行测试-SpringJUnit4ClassRunner来了

AopTest.java

package pl.grzejszczak.marcin.aop;import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import pl.grzejszczak.marcin.aop.service.UserService;
import pl.grzejszczak.marcin.aop.type.Role;
import pl.grzejszczak.marcin.aop.ui.SomeComponentForAdmin;
import pl.grzejszczak.marcin.aop.ui.SomeComponentForAdminAndGuest;
import pl.grzejszczak.marcin.aop.ui.SomeComponentForGuest;
import pl.grzejszczak.marcin.aop.ui.SomeComponentForWriter;
import pl.grzejszczak.marcin.aop.ui.UIFactory;
import pl.grzejszczak.marcin.aop.user.UserHolder;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:aopApplicationContext.xml" })
public class AopTest {@Autowiredprivate UIFactory uiFactory;@Autowiredprivate UserService userService;@Testpublic void adminTest() throws Exception {userService.setCurrentUser(new UserHolder(Role.ADMIN));Assert.assertNotNull(uiFactory.createComponent(SomeComponentForAdmin.class));Assert.assertNotNull(uiFactory.createComponent(SomeComponentForAdminAndGuest.class));Assert.assertNull(uiFactory.createComponent(SomeComponentForGuest.class));Assert.assertNull(uiFactory.createComponent(SomeComponentForWriter.class));}
}

和日志:

pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:26 Security Interceptor created
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:38 Intercepting creation of a component
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:48 Argument's class - [[class pl.grzejszczak.marcin.aop.ui.SomeComponentForAdmin]]
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:54 Annotation present - [@pl.grzejszczak.marcin.aop.annotation.SecurityAnnotation(allowedRole=[ADM])]
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:57 Security annotation is present so checking if the user can use it
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:70 Current user has required permissions for creating a component
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:38 Intercepting creation of a component
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:48 Argument's class - [[class pl.grzejszczak.marcin.aop.ui.SomeComponentForAdminAndGuest]]
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:54 Annotation present - [@pl.grzejszczak.marcin.aop.annotation.SecurityAnnotation(allowedRole=[ADM, GST])]
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:57 Security annotation is present so checking if the user can use it
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:70 Current user has required permissions for creating a component
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:38 Intercepting creation of a component
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:48 Argument's class - [[class pl.grzejszczak.marcin.aop.ui.SomeComponentForGuest]]
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:54 Annotation present - [@pl.grzejszczak.marcin.aop.annotation.SecurityAnnotation(allowedRole=[GST])]
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:57 Security annotation is present so checking if the user can use it
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:66 Current user doesn't have permission to have this component created
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:38 Intercepting creation of a component
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:48 Argument's class - [[class pl.grzejszczak.marcin.aop.ui.SomeComponentForWriter]]
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:54 Annotation present - [@pl.grzejszczak.marcin.aop.annotation.SecurityAnnotation(allowedRole=[WRT])]
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:57 Security annotation is present so checking if the user can use it
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:66 Current user doesn't have permission to have this component created

单元测试表明,对于给定的Admin角色,仅创建了前两个组件,而对于其他两个,则返回null(由于用户没有适当的权限)。 这就是在我们的项目中,我们如何使用Spring的AOP创建一个简单的框架,该框架将检查用户是否可以创建给定的组件。 由于对这些方面进行了编程,因此不必记住编写任何与安全相关的代码,因为它将为他完成。

参考: 安全性中的Spring AOP –通过我们的JCG合作伙伴 Marcin Grzejszczak(位于Blog上)上的代码瘾君子博客来控制UI组件的创建 。

翻译自: https://www.javacodegeeks.com/2013/04/spring-aop-in-security-controlling-creation-of-ui-components-via-aspects.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/368795.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

模拟生物自然进化的基因遗传算法

基因遗传算法&#xff08;Genetic Algorithm&#xff0c;GA&#xff09;是一种通过模拟生物进化过程来寻找最优解的优化算法。它是一种常见的启发式搜索算法&#xff0c;常用于优化、搜索和机器学习等领域。 生物基因遗传 生物的基因遗传是指父母通过基因传递给子代的过程。基因…

折半查找算法及分析(手工过程)

折半查找的手工过程&#xff1a; 1.我需要查找的数是10&#xff1b; 给定&#xff1a;1 5 8 10 13 14 17 22 25 27 29 31 35 37 40 42 45 47 50 51 58 下标&#xff1a;0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 1…

Bootstrap下拉菜单

前面的话 网页交互的时候经常会需要上下文菜单或者隐藏/显示菜单项&#xff0c;Bootstrap默认提供了用于显示链接列表的可切换、有上下文的菜单。而且在各种交互状态下的菜单展示需要和javascript插件配合才能使用。本文将详细介绍Bootstrap下拉菜单 使用方法 在使用Bootstrap框…

linux进程socket通信,linux进程间通信--socket套接字 实例代码

可以实现通信的代码实现&#xff0c;拿去用&#xff01;原文来自&#xff1a;http://blog.chinaunix.net/uid-26790551-id-3171897.html服务器端&#xff1a;#include #include #include #include #include #include #define UNIX_DOMAIN "/tmp/UNIX.domain"int main…

Maven发布到Nexus

1.概述 在本系列的上一篇文章中&#xff0c;我们将Maven设置为Nexus的部署过程 。 在本文中&#xff0c;我们将在项目的pom以及Jenkins作业中使用Maven配置发布过程 。 2. 为了使Maven能够发布到Nexus Repository Server&#xff0c;我们需要通过distributionManagement元素定…

mysql随机查询

select * from table as t1 join (select round(rand() * ((select max(id) from table)-(select min(id) from table))(select min(id) from table)) as id) as t2 where t1.id > t2.id order by t1.id limit 1;;转载于:https://www.cnblogs.com/upup2015/p/7782525.htm…

CSS学习笔记11 CSS背景

background-color&#xff1a;背景色 前面我们经常用background-color这个属性来设置元素的背景色&#xff0c;例如下面这条css可将段落的背景色设置为灰色 p {background-color: gray;} 如果想要元素的背景色向外延伸&#xff0c;则只需增加内边距即可 background-color可以为…

linux 文件的目录,Linux文件及目录管理

第七列&#xff1a;文件或目录名。名以 . 开头表示为隐藏文件或隐藏目录2.2 修改文件目录或者权限改变文件所属用户组&#xff1a;chgrpchgrp [-R] 用户组 文件或目录 ...[-R]&#xff1a;递归修改该目录下所有文件和目录&#xff1b;改变文件所有者&#xff1a;chownchown [-R…

Hbuilder MUI 下拉选择与时间选择器

一、 Hbuilder 下拉选择 <link rel"stylesheet" href"../../../assets/mui/css/mui.picker.min.css" /><script type"text/javascript" src"../../../assets/mui/js/mui.picker.min.js"></script> //引用mui.picker…

套接字(linux相关)

前言&#xff1a;略 一、前因 一切从tcp、udp开始。 众所周知&#xff0c;网络模型一般有两种模型&#xff0c;一种为OSI概念模型&#xff08;七层&#xff09;&#xff0c;另一种为TCP/IP网络模型&#xff08;四层&#xff09;。 TCP/IP应用层对应OSI的应用层、显示层、会话层…

Maven的春天

1.概述 本教程将讨论如何使用Maven设置Spring&#xff0c;并介绍使用Spring依赖项的特定用例。 最新的Spring版本可以在Maven Central上找到。 2.基本的Maven Spring依赖关系 Spring被设计为模块化和灵活的-基本的Spring容器可用于各种场景&#xff0c;而无需包含框架必须提供…

linux查看进程运行日志文件,【Linux】常用指令、ps查看进程、kill杀进程、启动停止tomcat命令、查看日志、查看端口、find查找文件...

1.说出 10 个 linux 常用的指令1) ls 查看目录中的文件2)cd /home 进入 / home 目录&#xff1b;cd .. 返回上一级目录&#xff1b;cd ../.. 返回上两级目录3)mkdir dir1 创建一个叫做 dir1 的目录4)rmdir dir1 删除一个叫做 dir1 的目录 (只能删除空目录)5)rm -f file1 删除一…

页面缓存之Meta http-equiv属性详解

http-equiv顾名思义&#xff0c;相当于http的文件头作用&#xff0c;它可以向浏览器传回一些有用的信息&#xff0c;以帮助正确和精确地显示网页内容&#xff0c;与之对应的属性值为content&#xff0c;content中的内容其实就是各个参数的变量值。 引用 meat标签的http-equiv…

Mysql存储过程详解

Mysql存储过程&#xff1a;1.1 定义&#xff1a;把复杂的操作&#xff0c;封装一个过程。类似于函数。 优点&#xff1a; 1、复杂操作&#xff0c;调用简单。 2、速度快。 缺点&#xff1a; 1、封装复杂。 2、没有灵活性。1.2 查看所有存储过…

E20171106-hm

pulldown adj. 折叠式的; pulldown menu 下拉菜单转载于:https://www.cnblogs.com/lancgg/p/8281683.html

Java PDF库

最近&#xff0c;我有一项任务是选择一些Java PDF库用于PDF生成。 但这不是一个简单的任务。 我想到的第一件事是iText。 众所周知Java库具有良好的声誉。 但是...有一些塞子。 iText 5版是在AGPL许可下发布的。 即&#xff0c;如果我们想在商业产品中使用iText&#xff0c;则必…

linux系统md5sum命令用不了,Linux中md5sum命令起什么作用呢?

摘要:下文讲述Linux中md5sum命令的功能说明&#xff0c;如下所示&#xff1b;md5sum命令功能:用于为一个文件生成其内容的MD5值&#xff0c;此命令的原理是对文件的内容进行校验,生成文件内容的MD5值此方式常用于检测文件是否被篡改(因为内容修改后&#xff0c;其MD5值会发生变…

前端工程师必备的几个实用网站

一、配色类网站 http://colorhunt.co 这个网站给我们提供了很多的配色方案&#xff0c;我们直接使用就OK了。使用方法也很简单&#xff0c;鼠标移动到对应的颜色上&#xff0c;我们就可以看到颜色的十六进制码&#xff0c;复制这个颜色到工具里就可以使用了。 https://webgra…

BZOJ1004 [HNOI2008]Cards 【burnside定理 + 01背包】

题目链接 BZOJ1004 题解 burnside定理 在\(m\)个置换下本质不同的染色方案数&#xff0c;等于每种置换下不变的方案数的平均数 记\(L\)为本质不同的染色方案数&#xff0c;\(m\)为置换数&#xff0c;\(f(i)\)为置换\(i\)下不变的方案数&#xff0c;那么\[L \frac{1}{m}\sum\li…

函数接口– Java 8中java.util.function包中的函数接口

我以前写过有关功能接口及其用法的文章。 如果您正在探索要成为Java 8一部分的API&#xff0c;尤其是那些支持lambda表达式的API&#xff0c;您会发现很少的接口&#xff0c;例如Function&#xff0c;Supplier&#xff0c;Consumer&#xff0c;Predicate和其他接口&#xff0c;…