2016-01-11 65 views
0

我正在設置Spring Boot(v1.2.6)web項目並使用Spring Security(v3.2.8)。我發現@PreAuthorize註釋非常方便,但我不知道是否有方法從註釋中的SpEL中讀取Boot屬性。我試圖做這種方式:@Preauthorize中的Spring Boot屬性

@PreAuthorize("mysecurity.permit") 

隨着application.yml聲明的屬性:

mysecurity: 
    permit: true 

但是我卻越來越

Failed to evaluate expression 'mysecurity.permit' 

我已經也嘗試了@mysecurity.permit${mysecurity.permit},結果也一樣。似乎可以在服務中聲明方法並以@service.isMySecurityPermited()的方式訪問它,但是我很樂意知道我是否能夠直接訪問該屬性。

回答

3

註釋中使用的值必須是常量。它們在編譯時進行評估,雖然它們可能在運行時保留下來,但不會重新評估。因此,您可以使用由SpEL評估的表達式,或者您可以編寫一個在註釋值中引用的幫助程序方法。

如果你看一下OnExpressionCondition的實現,你會注意到它獲得了傳遞給註解的值,在你的註釋中鏈接的情況下將會像@ConditionalOnExpression("${server.host==localhost} or ${server.port==8080} ")那樣註釋只是獲取文本值,它不知道文字代表什麼,它只是知道它是一個字符串。它在OnExpressionCondition中的註釋值的處理中,String值具有含義。他們獲取字符串值並將其傳遞給BeanExpressionResolver以供解析。

因此,在基於http://forum.spring.io/forum/spring-projects/security/100708-spel-and-spring-security-3-accessing-bean-reference-in-preauthorize的PreAuthorizement解決方案也將它傳遞給表達式處理器時,您應該能夠使用spring的表達式語言來引用任何bean屬性。

我不是一個情況,目前測試,但來自該線程好像你可以做類似

@Component 
public class MyBean { 
    @Value("${mysecurity.permit}") 
    private Boolean permit; 

    public boolean isPermitted() { return permit; } 

    @PreAuthorize("@myBean.isPermitted()") 
    public blah myMethod() { 
    // do stuff 
    } 
} 
+0

有道理,但Spring允許使用基於屬性的註釋。使用代理或相似的方式來實現,看看這個鏈接http://stackoverflow.com/questions/26451321/spring-boot-conditionalonproperty-or-conditionalonexpression http:// stackoverflow。com/questions/26394778/what-is-purpose-of-conditionalonproperty-annotation如果'@ PreAuthorized'註解可能會出現問題,我只是很煩惱。 –

+0

我想避免在一個bean變量中設置值,但總會給它一個嘗試。爲您的研究工作+1 ;-) –

0

這應該工作:

@Value("${mysecurity.permit}") 
private Boolean permit; 

然後使用:

@PreAuthorize(permit) 

但是,你需要正確設置配置文件,以使Spring能夠訪問它。在這裏閱讀: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

UPDATE: 你爲屬性佔位符配置豆? 例如:

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="locations"> 
    <list> 
     <value>classpath:com/foo/app.properties</value> 
    </list> 
    </property> 
</bean> 
+0

該物業在其他類別被確認(如'@ConditionalOnProperty(值= $ {mysecurity.permit}「)'),所以屬性本身不是問題,這個問題似乎是從'@ PreAuthorize'中訪問的。 –

相關問題