9

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

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

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

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

但我不知道如何使用@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)
4

3 回答 3

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>

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

于 2012-08-24T17:49:52.250 回答
0

听起来您想声明一个执行身份验证的 bean 的模拟版本。您可能需要一个测试 context.xml 来声明它。

于 2012-08-20T14:45:47.813 回答
0

也许检查这个旧帖子和官方文档16.3 Method Security Expressions for xml configuration。

我认为你需要在你的xml上声明:

您验证令牌的方法也可以是hasPermisions()。检查16.3.2 内置表达式

于 2012-08-24T08:49:32.783 回答