项目地址:
https://github.com/sevenyoungairye/spring-boot-study/tree/main/springboot-security-06
1. 使用授权和认证的必要性
- 什么是安全框架,干嘛的
安全框架,是为了保护web应用,保护用户的隐私,哪些东西能给别人看,而哪些不能给别人看。给别人看,需要达到哪些条件,比如需要登录,会员等级(充钱)。 - 什么是spring security
spring security 是针对spring项目的安全框架,也是spring boot底层安全模块默认的技术选型,他可以实现强大的web安全控制,对于安全控制,只需要引入spring-starter-security模块,进行少量的配置,即可实现强大的安全管理。
几个类:
-
WebSecurityConfigurerAdapter: 自定义Security策略
-
AuthenticationManagerBuilder:自定义认证策略
-
@EnableWebSecurity: 开启WebSecurity模式,@EnableXXXX开启某个功能
spring security 的两个主要目标是“认证”Authentication和“授权“Authorization(访问控制)
这两个概念相同,不只是在spring security中存在。
- 框架需要做的事
- 功能权限(理解为管理员和普通成员对应的功能)
- 访问权限(理解为需要授权,登录)
- 菜单权限 (理解为分角色)
2. spring security 与 shiro 与 过滤器,拦截器
只在使用方面比较:
spring security 简单易用,spring家族天然集成。
shiro属于阿帕奇,使用较为复杂,配置类较多,但功能强大。
过滤器,拦截器… 需要大量配置,大量判断,代码显得冗余。
3. 具体配置使用
一个配置类搞定
package cn.bitqian.config;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
* @description spring security test
* @author echo lovely
* @date 2020/10/25 19:46
*/
@EnableWebSecurity // 启用安全框架
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
// 授权
@Override
protected void configure(HttpSecurity http) throws Exception {
// 链式编程
http.authorizeRequests().antMatchers("/").permitAll(). // 首页允许所有人访问
antMatchers("/level1/**").hasRole("vip1"). // vip1才能访问level1..
antMatchers("/level2/**").hasRole("vip2").
antMatchers("/level3/**").hasRole("vip3");
// 没有权限默认会到登录页面,需要开启的登录页面
// 账号 密码 与 表单的name要一致
http.formLogin().loginPage("/login").loginProcessingUrl("/login"). // 指定一个特殊的页面登录!
usernameParameter("username").passwordParameter("password");
// 支持post请求
http.csrf().disable();
// 注销 退出登录到login 页面
http.logout().logoutSuccessUrl("/login");
// 记住我 cookie
http.rememberMe().rememberMeParameter("remember"); //记住我表单
}
// 认证方式
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 内存数据
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).
withUser("jack").password(new BCryptPasswordEncoder().encode("123")).roles("vip1", "vip2").
and().withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip1", "vip2", "vip3").
and().withUser("guest").password(new BCryptPasswordEncoder().encode("123")).roles("vip1");
}
}
更多请访问git。