2010-01-04 59 views

回答

1

Spring Security支持爲每個用戶分配一個或多個自定義角色。在我的網站上,我使用自定義表來保存這些角色,並設置身份驗證提供程序bean以從此表中選擇它們。查詢中的參數是他們的用戶名(這是我網站上的電子郵件地址)。我只把它設置爲支持每個用戶1個角色,但它可以很容易地分解成單獨的表格。

<authentication-provider> 
    <password-encoder hash="md5"/> 
    <jdbc-user-service data-source-ref="dataSource" 
     users-by-username-query="select email, password, '1' from user where email=?" 
     authorities-by-username-query="select email, role, '1' from user where email=?" /> 
</authentication-provider> 

一旦你建立角色,您可以爲您在您的控制器的角色,或JSP文件(使用http://www.springframework.org/security/tags標籤庫)。這裏有一個這樣的JSP的例子:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> 

<h2>Edit Comment</h2> 
<br/> 

<security:authorize ifNotGranted="ROLE_ADMIN"> 
You are not authorized to edit comments. 
</security:authorize> 
<security:authorize ifAnyGranted="ROLE_ADMIN"> 
    <!-- Display the whole admin edit comment page --> 
</security:authorize>