如何为Spring Security方法编写TestNG

这就是我的春季安全方法:

@Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission)
    {
        logger.trace(String.format("hasPermission() - \nAuthentication - %s\nObject - %s\nPermission Reqd - %s",
                authentication.toString(), targetDomainObject.toString(), permission.toString()));

        UserDetails principal = (UserDetails) authentication.getPrincipal();

        for (GrantedAuthority authority : principal.getAuthorities()) {
            if(authority.getAuthority().equalsIgnoreCase((String)permission)) {
                logger.debug("Allowing user to perform operation");
                logger.debug("Setting userId {} in the RO", principal.getUsername());
                if(targetDomainObject.getClass().isArray()) {
                    AbstractRO[] domainObjectArray = (AbstractRO[]) targetDomainObject;
                    for (AbstractRO abstractRO : domainObjectArray) {
                        abstractRO.setUserId(principal.getUsername());
                    }
                }
                return true;
            }
        }
        logger.debug("Dis-allowing user to perform operation. User does not have '{}' granted authority.", permission);
        return false;
    }

我把这个函数称为如下所示:

@PreAuthorize("isAuthenticated() and hasPermission(#request, 'CREATE_REQUISITION')")
    @RequestMapping(method = RequestMethod.POST, value = "/trade/createrequisition")
    public
    @ResponseBody
    void createRequisition(@RequestBody CreateRequisitionRO[] request);

这就是我的testNG类:

package in.hexgen.api.facade;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.testng.annotations.Test;

import com.hexgen.api.facade.security.HexGenPermissionEvaluator;

public class HexGenPermissionEvaluatorTest {
     private static final Logger logger = LoggerFactory.getLogger(HexGenPermissionEvaluatorTest.class);

  Object name="akash";
  Object permission="CREATE_REQUISITION";
  Authentication authentication;

  @Resource(name = "permissionEval")
  private HexGenPermissionEvaluator permissionEval;

  @Test
  public void hasPermission() {
      //authentication.setAuthenticated(true);

      logger.debug("HexGenPermissionEvaluator Generate - starting ...");
         permissionEval.hasPermission(authentication,name, permission);
      logger.debug("HexGenPermissionEvaluator Generate - completed ...");
  }

}

但是当我运行测试时,我得到了这个例外

FAILED: hasPermission
java.lang.NullPointerException
    at in.hexgen.api.facade.HexGenPermissionEvaluatorTest.hasPermission(HexGenPermissionEvaluatorTest.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:128)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1203)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1128)
    at org.testng.TestNG.run(TestNG.java:1036)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)

我犯了什么错误,请帮助我找到并解雇罪魁祸首.

最好的祝福

最佳答案 您需要手动设置
Authentication对象并在全局
SecurityContextHolder中设置它.您可以在类测试方法之前,每个方法之前或作为每个测试方法的一部分移动初始化.

@Before
public void setupAuth(){
    //password actually doesn't matter, meanwhile GrantedAuthorities should be necessary,
    //if you are using built-in checking functions such as "hasAnyRole" etc.
    List<GrantedAuthority> grantedAuthorities = Collections.emptyList();
    authentication = new UsernamePasswordAuthenticationToken(name, null, grantedAuthorities);

    //set authentication into static security context for proper handling by annotations
    SecurityContextHolder.getContext().setAuthentication(authentication);   
}

编辑:OP提供了有趣的resource,其中上述方法与IInvokedMethodListener一起使用,它允许对身份验证对象进行基于注释的控制.

点赞