2017-10-31 11 views
1

は、私のような方法で、多くの@RestController秒を持っている:(カスタムBean-Spelで@PreAuthorizeが有効かどうかをテストするには?

@PreAuthorize("@myBean.myMethod(#param1, #param2)") 
public void foo(String param1, Long param2) {} 

そしてどこか

@Component 
public class MyBean { 
    public boolean myMethod(String param1, Long param2) { 

     return importantSecurityCheck(); 
    } 
} 

それは非常によく私はリファクタリング後の可能な愚かなバグを回避したい作品をなど理由私の考えは、式が有効かどうかをチェックするテストを書くことでした(例えば、パラメータの型が同じで名前が有効な場合など)。

は、私はこのような何かしようとした:

@Test 
public void checkSecurityExpressions() { 
Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(RestController.class); 

    beansWithAnnotation.forEach((name, bean) -> { 
     Method[] methods = AopUtils.getTargetClass(bean).getMethods(); 

     for (Method method : methods) { 
      PreAuthorize annotation = method.getAnnotation(PreAuthorize.class); 

      if (annotation != null) { 

       String securityExpression = annotation.value(); 

       System.out.println(securityExpression); 
      } 

     } 
    }); 
} 

うまく表現を見つけたが、私は(冒頭でさえ@せずに、セキュリティコンテキストのない)単純な表現で仕事を見つけ、すべてExpressionParser例。

正確性をチェックするにはどうすればよいですか?それとも、この問題に対するより良い解決策がありますか?

答えて

0

最近、このようなテストケースをanswer another stack overflow questionに書き込む必要がありました。

を考える:

public class Foo { 

    public boolean isOk(String param) { 
     return "good".equals(param); 
    } 

    @PreAuthorize("@foo.isOk(#param1)") 
    public String bar(String param1) { 
     return "authOk"; 
    } 

} 

とテスト@Configurationクラスextends GlobalAuthenticationConfigurerAdapterこと:

@Override 
public void init(AuthenticationManagerBuilder auth) throws Exception { 
    auth.inMemoryAuthentication() 
     .withUser("foo").password("bar").roles("admin"); 
} 

その後:

@Autowired 
private Foo foo; 

@Test 
public void test() { 
    SecurityContext ctx = SecurityContextHolder.createEmptyContext(); 
    ctx.setAuthentication(new UsernamePasswordAuthenticationToken("foo", "bar")); 
    SecurityContextHolder.setContext(ctx); 
    assertThat(foo.bar("good")).isEqualTo("authOk"); 
    try { 
     foo.bar("bad"); 
     fail("Expected AccessDeniedException"); 
    } 
    catch (AccessDeniedException e) { 
     // expected 
    } 
} 

があなたの@PreAuthorize SPELを検証します。

関連する問題