如何在集成测试中模拟@PreAutorize标记?

Tho*_*vik 9 spring-mvc spring-security

我在Spring MVC中使用以下方法并使用Spring Security:

@PreAuthorize("#phoneNumber == authentication.name")
@RequestMapping(value = "/{phoneNumber}/start", method = RequestMethod.POST)
public ModelAndView startUpgrading(@PathVariable("phoneNumber") String phoneNumber,
       ....
}
Run Code Online (Sandbox Code Playgroud)

我设法模拟这样的身份验证:

public Authentication tryToAuthenticate(String accountName, String password) {
      UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(accountName, password);
    return authenticationManager.authenticate(token);
}
Run Code Online (Sandbox Code Playgroud)

但我不知道如何使用@PreAutorize设置授权.

如何正确设置我的测试上下文,以便我不会被拒绝访问?

org.springframework.security.access.AccessDeniedException: Access is denied
at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:83)
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:205)
Run Code Online (Sandbox Code Playgroud)

Jee*_*til 1

支持表达式属性以允许调用前和调用后授权检查的注释( @PreAuthorize、@PostAuthorize、@PreFilter、@PostFilter )通过 global-method-authority 命名空间元素启用。

您需要在 application-servlet.xml 或 security xml 文件中添加以下代码。

<security:global-method-security pre-post-annotations="enabled" >
    <security:expression-handler ref="expressionHandler"/>
</security:global-method-security>

<beans:bean id="expressionHandler"   class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
    <beans:property name="permissionEvaluator" ref="permissionEvaluator"/>
</beans:bean>
Run Code Online (Sandbox Code Playgroud)

检查 spring-testcontext-framework这篇文章回答的问题与您的非常相似。