目录
1. SpringSecurity 回顾
1.1 准备工作
准备 SpringMVC 的环境。发送请求访问资源时完全没有限制。
1.2 加入 SpringSecurity 环境
1.2.1 加入 SpringSecurity 依赖
<!-- SpringSecurity 对 Web 应用进行权限管理 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
<!-- SpringSecurity 配置 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
<!-- SpringSecurity 标签库 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
</dependency>
1.2.2 在 web.xml 中配置 DelegatingFilterProxy
<!-- SpringSecurity 的 Filter -->
<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>
注意:SpringSecurity 会根据 DelegatingFilterProxy 的 filter-name 到 IOC 容器中
查找所需要的 bean。所以 filter-name 必须是 springSecurityFilterChain 名字。
1.2.3 创建基于注解的配置类
// 注意!这个类一定要放在自动扫描的包下,否则所有配置都不会生效!
// 将当前类标记为配置类
@Configuration
// 启用 Web 环境下权限控制功能
@EnableWebSecurity
public class WebAppSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
// 与 SpringSecurity 环境下用户登录相关
}
@Override
protected void configure(HttpSecurity security) throws Exception {
// 与 SpringSecurity 环境下请求授权相关
}
}
1.3 放行首页和静态资源
security
.authorizeRequests() // 对请求进行授权
.antMatchers("/index.jsp") // 针对/index.jsp 路径进行授权
.permitAll() // 可以无条件访问
.antMatchers("/layui/**") // 针对/layui 目录下所有资源进行授权
.permitAll() // 可以无条件访问
.and()
.authorizeRequests() // 对请求进行授权
.anyRequest() // 任意请求
.authenticated() // 需要登录以后才可以访问
设置授权信息时需要注意,范围小的放在前面、范围大的放在后面。不然的话,小范围的设置会被大范围设置覆盖。
效果:未登录请求访问需要登录的请求时会看到 403 页面。
1.4 未认证请求跳转到登录页
security
……
.and()
.formLogin()
// 使用表单形式登录