spring-security通过认证类查询数据库中的表:
spring-security把用户在前端页面提交的用户名传参给认证类
认证类通过用户名在数据库中查询数据
认证类将查询结果返回给spring-security,
spring-security将认证类返回的数据和页面提交的数据进行比对,如果用户名和密码匹配就登录成功,不匹配则登录失败
导入依赖信息
<!-- 身份验证 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
配置web.xml:
- 扫描spring-security.xml
- 添加过滤器
<!-- 配置springSecurity安全过滤器 -->
<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>
配置spring-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<!-- 以下资源不被拦截 -->
<http pattern="/css/**" security="none"/>
<http pattern="/img/**" security="none"/>
<http pattern="/js/**" security="none"/>
<http pattern="/plugins/**" security="none"/>
<http pattern="/seller/add.do" security="none"/>
<http pattern="/*.html" security="none"/>
<!-- 页面拦截规则 -->
<http use-expressions="false">
<intercept-url pattern="/**" access="ROLE_SELLER" />
<form-login login-page="/shoplogin.html"
default-target-url="/admin/index.html" authentication-failure-url="/shoplogin.html"
always-use-default-target="true" />
<csrf disabled="true" />
<headers>
<frame-options policy="SAMEORIGIN" />
</headers>
<logout />
</http>
<!-- 认证管理器 -->
<authentication-manager>
<authentication-provider user-service-ref="userDetailService"/>
</authentication-manager>
<!-- 定义自定义认证类 -->
<beans:bean id="userDetailService" class="com.weilinyang.service.UserDetailsServiceImpl"/>
</beans:beans>
创建自定义认证类UserDetailsServiceImpl,并在spring-security.xml进行配置
自定义认证类要实现spring-security的接口UserDetailService
public class UserDetailsServiceImpl implements UserDetailsService {
@Reference
private SellerService sellerService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 构建角色列表
List<GrantedAuthority> grantAuths = new ArrayList<GrantedAuthority>();
grantAuths.add(new SimpleGrantedAuthority("ROLE_SELLER"));
//查询数据库的表
TbSeller seller = sellerService.findOne(username);
if (seller!=null){
return new User(username,seller.getPassword(),grantAuths);
}else{
return null;
}
}
}
seivice层就是根据用户名查询用户