SpringSecurity
一. 什么是SpringSecurity
1. 简单概述
-
用户登录系统时我们协助SpringSecurity将用户对应的角色,权限组装好,同时把各个资源所要求的权限设定好
剩下的登录验证和权限验证等工作都交给SpringSecurity
2. 相关概念
- 主体 principal
- 登录系统的用户
- 认证 authentication
- 确认系统登陆的身份,就是身份验证
- 授权 authorization
- 给用户分配权限
3.特点
- 与spring无缝整合
- 全面的权限控制
- 重量级的
- 要求:
- 不仅仅认证用户名和密码,角色和权限也必须是加载进来的,否则无法进行权限验证
二. 搭建SpringSecurity环境
1. 导入Security的依赖jar
-
<!-- SpringSecurity 对 Web 应用进行权限管理 --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>4.2.10.RELEASE</version> </dependency> <!-- SpringSecurity 配置 --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>4.2.10.RELEASE</version> </dependency> <!-- SpringSecurity 标签库 --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-taglibs</artifactId> <version>4.2.10.RELEASE</version> </dependency>
2.加入控制权限的Filter
-
SpringSecurity使用的是过滤器而不是拦截器
- 意味着其管理的包含了Web应用中的所有请求
- 项目中的静态资源也会被拦截,进行权限控制
-
<!-- 加入 SpringSecurity 控制权限的 Filter --> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <!-- 标 签 中 必 须 是 springSecurityFilterChain --> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
3. 创建配置类
-
使用默认的configure方法
- 会跳转去默认的登陆框进行验证
-
继承WebSecurityConfigurerAdapter重写configure方法
- 注意loginPage和loginProcessingUrl
-
// 该类一定要放在自动扫描的包下,否则所有配置都不会生效 @Configuration // 将当前类标记为配置类 @EnableWebSecurity // 启用Web环境下权限控制功能 public class WebAppSecurityConfig extends WebSecurityConfigurerAdapter { /** * 放行首页和静态资源 * @param security * @throws Exception */ @Override protected void configure(HttpSecurity security) throws Exception { security .authorizeRequests() // 对请求进行授权 .antMatchers("/index.jsp") // 针对/index.jsp路径进行授权 .permitAll() // 可以无条件访问 .antMatchers("/layui/**") // 表示layui下的任意资源 .permitAll() // 可无条件访问 .and() .authorizeRequests() // 对请求进行授权 .anyRequest() // 任意请求 .authenticated() // 需要登陆之后才可访问 .and() .formLogin() // 使用表单的形式登陆 // 关于loginPage:会影响到提交表单的地址,退出登陆地址,登陆失败地址 .loginPage("/index.jsp") // 指定登陆页面(如果没有指定会访问Security自带的) // 指定了loginProcessingUrl,就会覆盖loginPage方法中设置的默认值 .loginProcessingUrl("/do/login.html") // 指定提交登录表单的地址 ; } }
-
对于未授权的资源
.loginProcessingUrl("/do/login.html") // 指定提交登录表单的地址
;}
}
-
对于未授权的资源