1.1 实现步骤分析
- 明确需求:完成商家系统登录与安全控制,商家账号来自数据库,并实现密码加密。
- 简单分析:认证的提供者不能使用用户服务,而是来自数据库表。先整合SpringSecurity(配置依赖Jar包、web.xml配置文件、applicationContext-security.xml配置文件)
- 自定义认证类,在web层创建UserDetailsServiceImpl.java认证类实现UserDetailsService接口
- 认证类调用服务
1.2 配置与登录页面
1.2.1 配置文件
修改pom.xml,添加依赖
<!--配置SpringSecurity-->
<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加载文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext*.xml</param-value>
</context-param>
<!-- 配置Spring的核心监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置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>
sunny-shop-web/src/main/resources/applicationContext-security.xml
<?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:context="http://www.springframework.org/schema/context" 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://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--########## 配置请求URL拦截规则 ##########--> <!-- 配置哪些请求URL不被拦截 --> <security:http pattern="/*.html" security="none"/> <security:http pattern="/css/**" security="none"/> <security:http pattern="/img/**" security="none"/> <security:http pattern="/js/**" security="none"/> <security:http pattern="/plugins/**" security="none"/> <security:http pattern="/seller/save" security="none"/> <!-- 配置哪些请求URL需要拦截 --> <security:http> <!-- 配置剩余的请求地址都需要ROLE_SELLER角色才可以访问 --> <security:intercept-url pattern="/**" access="hasRole('SELLER')"/> <!-- 配置开启表单登录 --> <security:form-login login-page="/shoplogin.html" default-target-url="/admin/index.html"
always-use-default-target="true"
authentication-failure-url="/shoplogin.html"/>
<!-- 配置跨站请求伪造不可用-->
<security:csrf disabled="true"/>
<!-- 配置头信息,指定框架页策略(iframe子窗口也可以访问)-->
<security:headers>
<security:frame-options policy="SAMEORIGIN"/>
</security:headers>
<!-- 配置退出登录 -->
</