6

我想使用 Spring 安全性在我的 Web 应用程序中对用户进行身份验证。由于我不是 Spring 框架的成熟用户,我无法清楚地了解如何进行配置设置以使用 jdbc-user-service ..我做了以下配置。但它不工作

<authentication-manager>
    <authentication-provider>
         <jdbc-user-service data-source-ref="myDataSource"/>
    </authentication-provider>        
</authentication-manager>
<beans:bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <beans:property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <beans:property name="url" value="jdbc:mysql://localhost:3306/testDB"/>
    <beans:property name="username" value="admin"/>
    <beans:property name="password" value="admin"/>
</beans:bean>

..谁能帮我解决一个示例配置文件的问题。提前致谢。

4

3 回答 3

6

您通常使用自定义UserDetailsService. 这UserDetailsService是一个 DAO,用于在用户尝试登录时加载有关用户的数据。看看spring中的loadUserByUsername(String username)方法和UserDetails类。

你需要在你的上下文中定义它:

<bean id="myDetailsService"
    class="com.company.service.impl.MyDetailsService" />

要使用它,您可以将其添加到您的安全配置中:

<authentication-manager>
    <authentication-provider user-service-ref="myDetailsService" />
</authentication-manager>

你所有的安全过滤器都会使用它。

如果您需要帮助来实施它,您可以提出更具体的问题,但 IMO 不会有麻烦。

于 2011-08-24T07:56:47.757 回答
6

另一种方法是使用标准 spring 安全数据库模式 ( http://static.springsource.org/spring-security/site/docs/3.0.x/reference/appendix-schema.html ) 创建表。然后你可以简单地使用spring的jdbc-userservice:

<security:authentication-provider >
    <security:jdbc-user-service data-source-ref="dataSource" /> 
    <security:password-encoder hash="sha" />
</security:authentication-provider>

或者,如果您想使用自己的架构,您可以覆盖这样的查询:

<security:authentication-provider>
    <securiy:jdbc-user-service 
      data-source-ref="dataSource"
      users-by-username-query="select username, password from users where username=?"
      authorities-by-username-query="select username, roleName from role..."
      role-prefix="ROLE_"
    />
 </security:authentication-provider>
于 2011-08-24T10:45:14.437 回答
1

将这些行添加到您的<authentication-provider>标签中:

<authentication-provider>
    <password-encoder hash="sha-256" />
    <jdbc-user-service data-source-ref="dataSource"
            users-by-username-query="
                SELECT username, password, enabled
                FROM user WHERE username = ?"

            authorities-by-username-query="
                SELECT u.username, r.role_name
                FROM user u, user_role r, assigned_role a
                WHERE u.id = a.username
                AND r.id = a.role_id
                AND u.username = ?"
        />
</authentication-provider>

当然,您必须调整查询以匹配您的表名。

于 2012-06-08T13:42:57.463 回答