2010-01-04 38 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>