【问题标题】:How to simulate the @PreAutorize tag in a integration test?如何在集成测试中模拟@PreAutorize 标签?
【发布时间】:2012-08-15 14:07:03
【问题描述】:

我在 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)

【问题讨论】:

    标签: spring-mvc spring-security


    【解决方案1】:

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

    【讨论】:

    • 我已经有一个文本上下文 xml,没问题。知道哪个 bean 负责 Autorization 吗?
    • 您没有在 Spring 安全配置中指定它吗?
    【解决方案2】:

    也许检查this 旧帖子和official documentation xml 配置的 16.3 方法安全表达式。

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

    您验证令牌的方法也可以是 hasPermisions()。检查16.3.2 Built-In Expressions

    【讨论】:

      【解决方案3】:

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

      您需要在 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-frameworkthis post 回答的问题与你的非常相似。

      【讨论】:

      • 抱歉回复晚了,这很有效! 50赏金给你。感谢您的帮助!
      • @ThomasVervik ...我很高兴我的回答对您有所帮助。 :)
      猜你喜欢
      • 2019-12-07
      • 2011-09-30
      • 1970-01-01
      • 2012-04-25
      • 1970-01-01
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      • 2021-03-29
      相关资源
      最近更新 更多