1、jar包的依赖
<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> </dependency>
2、web.xml的配置
<!-- 配置springSecurity --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-security.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <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>
3、修改springSecurity的验证信息
Spring Security的AuthenticationManager用来处理验证的请求,处理的结果分两种:
- 验证成功:结果由AuthenticationSuccessHandler处理
- 验证失败:结果由交给AuthenticationFailureHandler处理。
/**最后在security.xml进行配置,注入spring容器中 * 将登录验证交予security,并且返回验证信息 * @author 86132 *与UserDetailsServiceImpl 配合使用 */ public class MyAuthenticationFailureHandle implements AuthenticationFailureHandler{ @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { Map<String,Object> map = new HashMap<>(2); map.put("success", false); //Bad credentials:密码错误 if("Bad credentials".equals(exception.getMessage())) { map.put("message", "密码错误"); }else { map.put("message", exception.getMessage()); } String result = JSON.json(map); response.setContentType("text/json;charset=utf-8"); response.getWriter().write(result); } }
4、自定义认证类
/** * 实现UserDetailsService接口来实现链接数据库 * @author 86132 * */ public class UserDetailsServiceImpl implements UserDetailsService{ //先通过dubbo来引入服务,再通过springSecurity注入,所以需要set方法 private SellerService sellerService; public void setSellerService(SellerService sellerService) { this.sellerService = sellerService; } //该类直接被springSecurity引用,url为login @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { //角色的集合 List<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("ROLE_SELLER")); //添加角色 //通过商家id获取商家对象 TbSeller seller = sellerService.findOne(username); if(seller != null) { //用户名存在 if(seller.getStatus().equals("1")) { //该用户已经通过审核 交给SpringSecurity进行密码的校验 return new User(username, seller.getPassword(), authorities); }else { throw new BadCredentialsException("您的账号审核中...."); } }else { //当用户名不存在时 throw new BadCredentialsException("用户名不存在"); } } }
5、spring.xml的配置
将上述的自定义验证类和自定义认证类注入,同时为了密码安全,还会注入BCrypt算法加密.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd"> <!-- 设置以下的页面不拦截 --> <security:http pattern="/*.html" security="none"></security:http> <security:http pattern="/css/**" security="none"></security:http> <security:http pattern="/img/**" security="none"></security:http> <security:http pattern="/js/**" security="none"></security:http> <security:http pattern="/plugins/**" security="none"></security:http> <!-- 注册页面需要执行seller里的add.do(商家注册),所以add.do也需要放行 --> <security:http pattern="/seller/add.do" security="none"></security:http> <!-- 拦截规则 --> <security:http use-expressions="false"> <!-- access:必须以ROLE_开头 --> <security:intercept-url pattern="/**" access="ROLE_SELLER"/> <!-- login-page:默认登陆页面 default-target-url:登录成功后跳转页面 authentication-failure-url:认证失败后跳转页面 Spring Security默认是使用SimpleUrlAuthenticationFailureHandler,在配置中修改为自定义的myAuthenticationFailureHandle。 --> <security:form-login login-page="/shoplogin.html" default-target-url="/admin/index.html" authentication-failure-handler-ref="myAuthenticationFailureHandle" authentication-failure-url="/shoplogin.html" always-use-default-target="true"/> <!-- 关闭csrf:关闭防止盗链 --> <security:csrf disabled="true"/> <!-- 将前端框架放行,避免404 --> <security:headers> <security:frame-options policy="SAMEORIGIN"/> </security:headers> <!-- 添加注销的功能,默认注销的url是/logout,注销成功后跳转到默认登陆页面 --> <security:logout/> </security:http> <!-- 认证管理器 --> <security:authentication-manager> <security:authentication-provider user-service-ref="userDetailsService"> <security:password-encoder ref="bCryptPasswordEncoder"/> </security:authentication-provider> </security:authentication-manager> <!-- 配置dubbo --> <dubbo:application name="jd-shop-web"/> <!-- 指定注册中心的地址 --> <dubbo:registry address="zookeeper://192.168.25.128:2181"></dubbo:registry> <!-- 引用服务 --> <dubbo:reference id="sellerService" interface="com.jd.sellergoods.service.SellerService"></dubbo:reference> <bean id="userDetailsService" class="com.jd.shop.service.impl.UserDetailsServiceImpl"> <property name="sellerService" ref="sellerService"></property> </bean> <bean id="myAuthenticationFailureHandle" class="com.jd.shop.security.MyAuthenticationFailureHandle"></bean> <!-- 配置BCrypt --> <bean id="bCryptPasswordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"></bean> </beans>
BCrypt算法加密的使用方法:
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String password = passwordEncoder.encode(seller.getPassword()); seller.setPassword(password);