Spring Security 是一个功能强大且高度可定制的身份验证和访问控制框架。它是保护基于 Spring 的应用程序的事实标准。
Spring Security 是一个专注于为 Java 应用程序提供身份验证和授权的框架。像所有 Spring 项目一样,Spring Security 的真正强大之处在于它可以轻松扩展以满足自定义需求
- 认证(Authentication)
- 系统认为用户是否能登录
- 授权(Authorization)
- 系统判断用户是否有权限去做某些事情
- 和 Spring 无缝整合
- 对身份验证和授权的全面且可扩展的支持
- 轻量级
- Shiro 主张的理念是把复杂的事情变简单。针对对性能有更高要求的互联网应用有更好表现。
- 通用性
- 好处:不局限于Web 环境,可以脱离Web 环境使用
- 缺陷:在Web 环境下一些特定的需求需要手动编写代码定制
-
优点:
- Spring Security基于Spring开发,项目中如果使用Spring作为基础,配合Spring Security做权限更加方便,而Shiro需要和Spring进行整合开发
- Spring Security功能比Shiro更加丰富些,例如安全防护
- Spring Security社区资源比Shiro丰富
-
缺点:
- Shiro的配置和使用比较简单,Spring Security上手复杂
- Shiro依赖性低,不需要任何框架和容器,可以独立运行,而Spring Security依赖于Spring容器
注意:页面是整合SpringSecurity提供,默认用户名为user,密码为运行是生成密码
-
配置账号密码
spring: security: user: name: admin password: 123 -
编写controller
@Controller @RequestMapping("/user") public class UserController { @GetMapping("/hello") public String login() { return "success"; } } -
编写thymeleaf
Title login success
-
测试
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
BCryptPasswordEncoder bCryp = new BCryptPasswordEncoder();
String pwd = bCryp.encode("123");
auth.inMemoryAuthentication().withUser("zs").password(pwd).roles("admin");
}
}
2.2.3 自定义实现类
1.UserDetailsService 接口
当什么也没有配置的时候,账号和密码是由 Spring Security 定义生成的。而在实际项目中账号和密码都是从数据库中查询出来的。 所以我们要通过自定义逻辑控制认证逻辑
如果需要自定义逻辑时,只需要实现 UserDetailsService 接口即可
-
返回值 UserDetails
- 这个接口是系统默认的用户“主体”
- 主体:使用系统的用户或设备或从其他系统远程登录的用户等等。简单说就是谁使用系统谁就是主体
// 表示获取登录用户所有权限 Collection extends GrantedAuthority> getAuthorities(); // 表示获取密码 String getPassword(); // 表示获取用户名 String getUsername(); // 表示判断账户是否过期 boolean isAccountNonExpired(); // 表示判断账户是否被锁定 boolean isAccountNonLocked(); // 表示凭证{密码}是否过期 boolean isCredentialsNonExpired(); // 表示当前用户是否可用 boolean isEnabled();- 实现类User
public User(String username, String password, Collection extends GrantedAuthority> authorities) { this(username, password, true, true, true, true, authorities); } - 这个接口是系统默认的用户“主体”
@Service("userDetailsService")
public class MyDetailService implements UserDetailsService {
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 1.模拟根据用户名从数据库中取值
if (!"root".equals(username)) {
throw new UsernameNotFoundException("用户名不存在");
}
// 2.获取密码的密文
//String pwd = "$2a$10$lX2YpIyaP.bTV2IBJDSmd.R6TF0VeE5HO5gfliJQB6yuI1aHSv50u";
String pwd = bCryptPasswordEncoder.encode("123");
// 创建User对象,并返回
return new User(username,pwd, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
}
}
public class UserController {
@GetMapping("/login1")
public String login1() {
return "login1";
}
@GetMapping("/index")
public String success() {
return "success";
}
@GetMapping("/error")
public String error() {
return "error";
}
}
@Configuration
public class SecurtiyConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 使用自定义的实现类来实现认证
auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() // 表单的登录
.loginPage("/user/login1") // 登录页面地址 - controller中跳转到login页面的地址
.loginProcessingUrl("/user/index") // 登录的地址 - form表单中active地址
.defaultSuccessUrl("/user/index") // 成功之后跳转地址.successForwardUrl 这个提交方式因为从post到get会出现异常
.failureForwardUrl("/user/error"); // 发生了异常之后的跳转地址
http.authorizeRequests()
.antMatchers("/user/login1") //表示配置请求路径
.permitAll() // 指定 URL 无需保护。
.anyRequest() // 其他请求
.authenticated(); //需要认证
// 关闭 csrf
http.csrf().disable();
}
}
3.使用数据库
-
准备工作
-
添加MyBatisPlus依赖
com.baomidou mybatis-plus-boot-starter 3.0.5 -
启动类上添加注解
@ComponentScan("cn.blb") @MapperScan("cn.blb.security.mapper") -
数据库的配置
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/security?serverTimezone=GMT%2B8 username: root password: root -
新建实体类
@Data public class SysUser implements Serializable { private static final long serialVersionUID = 915478504870211231L; private Integer id; //账号 private String account; //用户名 private String userName; //用户密码 private String password; //上一次登录时间 private Date lastLoginTime; //账号是否可用。默认为1(可用) private Boolean enabled; //是否过期。默认为1(没有过期) private Boolean accountNonExpired; //账号是否锁定。默认为1(没有锁定) private Boolean accountNonLocked; //证书(密码)是否过期。默认为1(没有过期) private Boolean credentialsNonExpired; //创建时间 private Date createTime; //修改时间 private Date updateTime; //创建人 private Integer createUser; //修改人 private Integer updateUser; } -
修改loadUserByUsername
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // 1.根据用户名从数据库中取值 QueryWrapperwrapper = new QueryWrapper<>(); wrapper.eq("user_name", username); SysUser sysUser = userMapper.selectOne(wrapper); // 如果对象null表示数据库中没有这个字段 if (sysUser == null) { throw new UsernameNotFoundException("用户名不存在"); } // 2.获取密码的密文 //String pwd = "$2a$10$lX2YpIyaP.bTV2IBJDSmd.R6TF0VeE5HO5gfliJQB6yuI1aHSv50u"; String pwd = new ByptPasswordEncoder().encode(sysUser.getPassword()); // 3.根据用户名获取权限集合 // @TODO // 创建User对象,并返回 return new User(username, pwd, AuthorityUtils.commaSeparatedStringToAuthorityList("admin")); } -
修改SecurityConfig
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(password()); } @Bean public BCryptPasswordEncoder password() { return new BCryptPasswordEncoder(); } }@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(password()); } @Bean public BCryptPasswordEncoder password() { return new BCryptPasswordEncoder(); }}
-



