本文为转载学习java
原文连接:http://blog.csdn.net/dsundsun/article/details/11946949正则表达式
@RolesAllowed("ROLE_USER")
spring
public void changePassword(String username, String password); express
或编程
@RolesAllowed({"ROLE_USER","ROLE_ADMIN"})
public void changePassword(String username, String password);安全
"正如咱们可能推断出的那样,@RolesAllowed注解并不支持SpEL 表达式。学习
"JSR-250还有两个其它的注解:@PermitAll 和@DenyAll。它们的功能正如你所预想的,容许和禁止对方法的任何请求。spa
在看一下@Secured注解实现方法安全:.net
<global-method-security secured-annotations="enabled"/>
由于@Secured与JSR标准的@RolesAllowed注解在功能上一致,因此并无充分的理由在新代码中使用它,可是它可以在Spring的遗留代码中运行代理
还有一种,AOP技术:
实现方法安全的最后一项技术也多是最强大的方法,它还有一个好处是不须要修改源代码。做为替代,它使用面向方面的编程方式为一个方法或方法集合声明切点(pointcut),而加强(advice)会在切点匹配的状况下进行基于角色的安全检查。AOP的声明只在Spring Security的XML配置文件中并不涉及任何的注解。
<global-method-security> <protect-pointcut access="ROLE_ADMIN" expression="execution(* com.packtpub.springsecurity.service.IUserService.*(..))"/> <protect-pointcut access="ROLE_ADMIN" expression="execution(* com.packtpub.springsecurity.service.I*Service.*(..))"/> </global-method-security>
比较方法受权的类型:
如下这段话值得注意:
强烈建议在接口上声明AOP规则(以及其它的安全注解),而不是在实现类上。使用类(经过Spring的CGLIB代理)进行声明可能会致使应用出现不可预知的行为改变,一般在正确性方面比不上在接口定义安全声明(经过AOP)。
spring security还提供了一种方式:
xmlns:security="http://www.springframework.org/schema/security"(声明) <bean id="userService" class="com.packtpub.springsecurity.service.UserServiceImpl"> <security:intercept-methods> <security:protect access="ROLE_USER" method="changePassword"/> </security:intercept-methods> </bean>
这种方式能够在配置文件上直接指定哪一个方法须要哪一个属性,不过书中这样描述它:
尽管阅读起来很容易,可是这种方式的方法安全声明在表现性上不如切点,在功能上不如咱们已经见过的注解方式。可是,对于必定类型的工程,使用XML声明的方式足以知足你的需求。
可使用简单的通配符来注明方法名,如,咱们能够用以下的方式保护给定bean里全部的set方法:
<security:intercept-methods> <security:protect access="ROLE_USER" method="set*"/> </security:intercept-methods>
方法名匹配能够包含前面或后面的正则表达式匹配符(*)。这个符号的存在乎味着要对方法名进行通配符匹配,为全部匹配该正则表达式的方法添加拦截器。注意,其它经常使用的正则表达式操做符(如?或[)并不支持。请查阅相关的Java 文档以理解基本的正则表达式。更复杂的通配符匹配或正则匹配并不支持。
@PreAuthorize("#username == principal.username and hasRole('ROLE_USER')") public void changePassword(String username, String password);
“Spring Security方法注解所绑定的SpEL支持更复杂的表达式,包括含有方法参数的表达式。