spring security的安全配置都是通过继承WebSecurityConfigurerAdapter,重载configure方法来实现
方法 | 描述 |
configure(HttpSecurity http) | 通过拦截器来保护服务器请求 |
configure(AuthenticationManagerBuilder auth) | 配置用户登录的信息(用户名和密码是否正确等) |
configure(WebSecurity web) | 配置Spring Security的Filter链 |
1 拦截所有请求,无用户信息
注:
(1) 配置这样spring security的安全配置会拦截所有请求,并且没有配置用户相关信息,导致所有人都无法访问;
(2) 这里可以删除调@EnableWebMvc
2 拦截所有请求,内存配置用户名称和密码
注:
(1) 配置这样spring security的安全配置会拦截所有请求,会根据配置用户和密码可以访问请求
(2) 密码必须要用BCryptPasswordEncoder类加密一下,否则,后台会报 There is no PasswordEncoder mapped for the id "null" 错误
(3) 这里可以删除调@EnableWebMvc
3 基于登录页面,用户名称和密码基于内存,并配置静态资源服务路径
注:
(1) 登录 /login 请求可以不在控制层写,根据配置项就可以;
(2) 默认的登录成功后路径 defaultSuccessUrl("/index", true) 的第二参数为true,只要登录就会服务 /index 路径,若不配就是之前进入登录页面的服务路径
(3) antMatchers("/enter","/login").permitAll() 是指不拦截该请求;
(4) csrf().disable() 若没有配置,会导致只要登录会一直报302 ,然后停留在登录页面(防止跨域攻击);
(5) spring boot的静态资源会默认在/resources/static下面,若加@EnableWebMvc注解需要自己配置;
(6) web.ignoring().antMatchers("/png/**") 表示可以通过 /png 开头的请求,去访问static下面的静态资源如图片,js,css等
4 基于登录页面,用户名称和密码基于数据库,并配置静态资源服务路径
spring security的配置类
业务实现层 (需要实现UserDetailsService重写loadUserByUsername方法,UserService是自己写接口非必须实现)
用户实体类(需要实现UserDetails接口)
注:
(1) auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
必须要使用BCrypt加密方式加密密码,即数据库密码是BCrypt加密方式加密的,否则报There is no PasswordEncoder mapped for the id "null"
(2) 可以使用如下代码获取当前登录用户信息
@RequestMapping("/getUser")
@ResponseBody
public User getUser(Authentication authentication) {
User user = (User) authentication.getPrincipal();
return user;
}