基于Spring Security和数据库的身份验证和权限授权检查
这是一个基于Spring Security和MySQL数据库的服务器后端资源用户身份登录验证和URL权限验证的源码程序,比较简单,适合RESTful等各种后端资源的安全保护。
首先在web.xml中配置一个过滤器,这是对指定URL资源进行授权验证,访问这些URL必须输入用户名和密码或者已经登录验证并且有权限访问这些URL资源。
web.xml
<!-- Security Filters and their Mappings. -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
SpringContext-Security.xml
<security:http auto-config='true'>
<security:intercept-url pattern="/**" access="ROLE_USER, ROLE_ADMIN" />
<security:http-basic />
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:jdbc-user-service data-source-ref="dataSource"
users-by-username-query="
select username,password, enabled
from users where USERNAME=?"
authorities-by-username-query="
select u.username, ur.authority from users u, user_roles ur
where u.user_id = ur.user_id and u.username =? "
/>
</security:authentication-provider>
</security:authentication-manager>
在这个配置中提供对你的用户名和密码数据表进行查询的SQL,第一个SQL是根据用户名查询,主要用于登录login,验证用户身份,第二个也是根据用户名查询,主要是查询用户对该URL是否有权限访问。
SpringContext-Database.xml
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="admin" />
<property name="password" value="admin" />
</bean>
这是配置Spring数据库连接,上面的根据用户名查询的SQL语句需要针对具体数据库实施,这里配置的是MySQL。