SpringSecurity
一、SpringSecurity是什么?
Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。
二、之前认证授权
1.1什么是认证
类似用户登录,对用户名和密码进行判断。
1.2.什么是授权
访问的页面需要登录和需要相应的权限。为用户添加访问默写页面或者某些操作的权利。给某些页面设置访问的权限。
1.3认证流程
用户直接登录,根据用户名到数据库中去搜索。
查询成功返回对象,在判断密码,是否正确。
登录成功后,将登录成功信息记录在session中。
1.4认证检查
每次访问都携带登录信息,后台对session中的登录信息验证。
1.5授权检查
设置拦截器,与登录拦截器一样,对需要权限的路径进行拦截。拦截到后到去查询该登录的用户是否拥有这路径的访问操作权限。
三、Security认证入门
1搭建项目导入依赖
maven依赖(示例):
springboot父工程
springboot的web包
security包
测试包
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
2.启动类
@SpringBootApplication
@MapperScan("cn.XXX.security.mapper")
@EnableTransactionManagement
public class SecurityServiceApp {
public static void main(String[] args) {
SpringApplication.run(SecurityServiceApp.class);
}
}
3.security配置
1.定义一个类集成WebSecurityConfigurerAdapter
2.开启Security: @EnableWebSecurity
3.注册一个UserDetailsService(基于内存)
4.定义编码器PasswordEncoder:(不加密)
5.覆写configure
Security自定义认证
1.自定义MyUserDetailsService 实现 UserDetailsService接口,覆写loadUserByUsername
1.根据用户名查询用户信息
2.查询用户的权限
3.把用户信息和权限封装到UserDetails返回
2.修改密码编码器,使用BCryptPasswordEncoder
3.拷贝一个static/login.html
4.修改 HttpSecurity 配置
登陆页面路径url
登陆处理地址url
登录页面放行
4.1
- web授权
- 1.改造userDetailsService从数据库加载用户和权限
- 2.配置httpSecurity
+ 1.查询所有权限
+ 2.循环权限,为资源授权
- 方法授权
1.注释掉web授权代码
2.开启方法授权支持
@EnableGlobalMethodSecurity(prePostEnabled = true)
3.方法贴授权注解
@PreAuthorize(“hasAuthority(‘dept:list’)”)
5.认证授权结果处理
接口认识
AuthenticationSuccessHandler:认证成功处理器
AuthenticationFailureHandler:认证失败处理器
AccessDeniedHandler:授权失败处理器
AuthenticationEntryPoint:匿名用户授权失败处理器
认证成功处理
1.写个类,实现AuthenticationSuccessHandler
2.覆写方案,返回JSON结果
3.security配置处理器
.successHandler(new MyAuthenticationSuccessHandler()) //认证成功处理器
认证失败处理
1.写个类,实现AuthenticationFailureHandler
2.覆写方案,返回JSON结果
3.security配置处理器
.failureHandler(new MyAuthenticationFailureHandler())
授权失败
1.写个类,实现AccessDeniedHandler
2.覆写方案,返回JSON结果
3.security配置处理器
记住我
1.登录页面增加记住我复选框
2.数据库搞张表persistent_logins
3.配置类:注册一个PersistentTokenRepository
4.配置类:配置remeber-me
总结
提示:SpringSecurity 做权限,我们要做的只需要写配置类和UserDetailsService的实现类,以及成功和失败的类。大大的方便了我们做权限。