近日在使用SpringSecurity的项目中发现一个小问题,就是在接口上加了@Secured标注限制调用接口权限时,某些JUnit无法正常调用了。

例如:

	@Secured(PrivilegeDAO.ROLE_REMIND_CREATE)
public Serializable save(Users user) throws BusinessException;

  

调用save方法时,必须具备 PrivilegeDAO.ROLE_REMIND_CREATE权限才行。

原因很简单,执行JUnit的时候并没有经过SpringSecurity的登录把资源设置到上下文,所以是无登录权限的。而调用接口的时候又要获取执行权限,这当然造成无法调用的局面了。

花了点时间,查找资源,找到个解决方案,分享下。其实就是覆盖原来认真配置信息,然后把供单元测试用的TestingAuthenticationToken设置回spring容器当中。所以之后执行单元测试时就有权限了。注意构造TestingAuthenticationToken的时候必须根据项目具体情况来添加GrantedAuthority[]。

具体代码参考如下:

import java.util.ArrayList;
import java.util.Collection;
import java.util.List; import org.springframework.beans.factory.BeanFactory;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.TestingAuthenticationProvider;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl; import cn.com.timekey.drugmonitor.po.Privilege; /**
* @author kennylee
*
*/
public class SecurityTestingUnit { /**
* 设置SpringSecurity的登录用户权限。
*
* @param ctx
* @param auths
*/
public static void setAuthToken(BeanFactory ctx, GrantedAuthority[] auths) {
TestingAuthenticationToken token = new TestingAuthenticationToken(
"admin", "test", auths);
// Override the regular spring configuration
ProviderManager providerManager = (ProviderManager) ctx
.getBean("authenticationManager");
List<AuthenticationProvider> list = new ArrayList<AuthenticationProvider>();
TestingAuthenticationProvider testingAuthenticationProvider = new TestingAuthenticationProvider();
list.add(testingAuthenticationProvider);
providerManager.setProviders(list); // Create and store the SpringSecurity SecureContext into the
// SecurityContextHolder.
SecurityContextImpl secureContext = new SecurityContextImpl();
secureContext.setAuthentication(token);
SecurityContextHolder.setContext(secureContext);
} /**
* 构造权限组
*
* @param rolePrivileges
* @return
*/
public static GrantedAuthority[] generateAuthorities(
Collection<Privilege> privileges) {
GrantedAuthority[] auths = new GrantedAuthority[privileges.size()];
if (!privileges.isEmpty()) {
int count = 0;
for (Privilege rolePrivilege : privileges) {
String privilegeName = rolePrivilege.getPrivilegeName();
GrantedAuthority authority = new GrantedAuthorityImpl(
privilegeName);
auths[count] = authority;
count++;
}
}
return auths;
} }

  

其中generateAuthorities只是我的一个辅助构造方法。不是重点内容。setAuthToken为主体代码。

JUnit testing with Acegi Security

Here's a tip if you are trying to do some unit testing with Acegi Security - particularly if you are doing role based authorization of method calls on your manager objects via interception.

Basically, a secure method interceptor will a) need an authentication token to play with, and b) a way to  find out what authorities the user has.  We need to cater for this when running the tests.

Acegi Security conveniently provides a TestingAuthenticationToken for unit testing purposes so we are Ok with the token part. You will now need to provide a suitable authentication provider. Somewhat unsurprisingly, there is a TestingAuthenticationProvider that you can add to your Spring config file to accommodate this.

But here is the problem: we already have this configured for production using a different provider (obviously), so we would have to resort to changing the config files depending on if you are running tests or not. This is too fragile for me, so here is the essence of the tip: leave the configuration file alone and dynamically changes the provider in the setup of the unit test.

Here is some code that I have in my JUnit setUp() method:

        // Grant all roles to noddy.
TestingAuthenticationToken token = new TestingAuthenticationToken(
"noddy", "test", new GrantedAuthority[] {
new GrantedAuthorityImpl("User"),
new GrantedAuthorityImpl("Administrator") }); // Override the regular spring configuration
ProviderManager providerManager = (ProviderManager) ctx.getBean("authenticationManager");
List list = new ArrayList();
list.add(new TestingAuthenticationProvider());
providerManager.setProviders(list); // Create and store the Acegi SecureContext into the ContextHolder.
SecureContextImpl secureContext = new SecureContextImpl();
secureContext.setAuthentication(token);
ContextHolder.setContext(secureContext);
So... it sets up an authentication token, then resets the authentication managers' provider list with one that contains the TestingAuthenticationProvider. It then creates the context for the method execution. The problem with this is it does it for every single test method - that is how JUnit works for better or worse. Hope it proves useful for you.

  

参考见:http://fishdujour.typepad.com/blog/2005/02/junit_testing_w.html

编写使用SpringSecurity的JUnit测试提醒的更多相关文章

  1. 单元测试实战 - Junit测试

    一.对加法函数进行测试 1.实例化被测单元(方法):类名 实例名=new 类名([参数]) 2.调用被测单元,对比预期值和输出值(实际值): 在没有junit测试工具的情况下,我们要进行如下的测试代码 ...

  2. EditBox问题的实现以及Junit测试框架的简要说明

    一.这周的EditBox由一个框改为三个框,同时进行测试,下面给出程序及截图 1 import java.util.regex.Matcher; 2 import java.util.regex.Pa ...

  3. Android Junit测试框架

    对应用进行单元测试: 使用Junit测试框架,是正规Android开发的必用技术.在Junit中可以得到组件,可以模拟发送事件和检测程序处理的正确性. 1.配置指令集和函数库: (1)配置指令集,指定 ...

  4. 无废话Android之android下junit测试框架配置、保存文件到手机内存、android下文件访问的权限、保存文件到SD卡、获取SD卡大小、使用SharedPreferences进行数据存储、使用Pull解析器操作XML文件、android下操作sqlite数据库和事务(2)

    1.android下junit测试框架配置 单元测试需要在手机中进行安装测试 (1).在清单文件中manifest节点下配置如下节点 <instrumentation android:name= ...

  5. applicationContext.xml文件放置位置不同而导致的jUnit测试的时候路径的不同

    如果applicationContext.xml文件放置在src下面的的时候使用jUint测试的时候编写的路径应该是这样的: @Test public void testFindByPage() { ...

  6. 使用Cobertura统计JUnit测试覆盖率

    这是一个JavaProject,关于Cobertura的用法详见代码注释 首先是应用代码(即被测试的代码) package com.jadyer.service; public class Calcu ...

  7. junit测试Android项目

    关于junit测试Android项目方法主要有一下步骤: 1.导入junit4的jar包 在工厂中Build Path中Add Library->JUnit->JUnit4->Fin ...

  8. Java进阶(五)Junit测试

    我们在编写大型程序的时候,需要写成千上万个方法或函数,这些函数的功能可能很强大,但我们在程序中只用到该函数的一小部分功能,并且经过调试可以确定,这一小部分功能是正确的.但是,我们同时应该确保每一个函数 ...

  9. Java高级特性 第10节 IDEA和Eclipse整合JUnit测试框架

    一.IDEA整合Junit测试框架 1.安装插件 打开File菜单的下拉菜单settings[设置] : 点击左侧Plugins[插件]菜单 在输入框中输入JUnitGenerator 2.0,点击I ...

随机推荐

  1. codeforces #round363 div2.C-Vacations (DP)

    题目链接:http://codeforces.com/contest/699/problem/C dp[i][j]表示第i天做事情j所得到最小的假期,j=0,1,2. #include<bits ...

  2. Cisco ASA 5505 Routing Between Two (Internal) VLANS

    Referenced:http://www.petenetlive.com/KB/Article/0000869 Problem I had to set this up for a client t ...

  3. select2美化下拉单

    http://www.51xuediannao.com/js/jquery/select2.html http://www.51xuediannao.com/demo.php

  4. Camelot_floyd&&DP

    Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 3119   Accepted: 1455 Description Centu ...

  5. 【转发】构建高可伸缩性的WEB交互式系统(下)

    原文转自:http://kb.cnblogs.com/page/504518/ 本文是<构建高可伸缩性的WEB交互式系统>系列文章的第三篇,以网易的NEJ框架为例,对模块的可伸缩性进行分析 ...

  6. C#山寨版本【天翼拨号客户端】---内含详细抓包,模拟数据---万事俱备,只欠东风。

    官方的客户端的最大缺点: 1.一台电脑不允许使用同时启动多个网卡(目的是禁止使用虚拟WIFI或通过网卡后共享网络到路由器?): 2.使用路由器无法拨号(提示:不允许NAT后登录) 3.之前用某哥们破解 ...

  7. spark读hdfs文件实现wordcount并将结果存回hdfs

    package iie.udps.example.operator.spark; import scala.Tuple2; import org.apache.spark.SparkConf; imp ...

  8. java中byte数据转换为c#的byte数据

    最近在做下载方面的开发.有一个需求,就是读取要下载的文件中的一些数据,比如要读取这个文件包含的用户信息,但是怎么读都不对.后来搞了很久才发现,服务器上的文件里的用户信息,用C#写的存储方法来存储的,而 ...

  9. Apache、tomcat、Nginx常用配置合集

    配置文件地址: Apache: /etc/httpd/conf/httpd.conf tomcat: /usr/local/tomcat/conf/server.xml Nginx  : /usr/l ...

  10. SAP保存操作记录CDHDR和CDPOS表

    http://blog.sina.com.cn/s/blog_7dce1fac01014yp2.html转自sap的字段和对象的修改都会保存旧值,数据保存在CDHDR和CDPOS表中,提取旧值可以采用 ...