视频教程地址: https://www.bilibili.com/video/BV1kT4y1F7Tc
代码地址: https://gitee.com/crazyliyang/video-teaching
1. 核心配置类 WebSecurityConfigurerAdapter
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true) // 注意
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests() // 配置请求地址的权限
.antMatchers("/demo").permitAll() // 所有用户可访问,无需登录认证, @PermitAll 功能一样
.antMatchers("/config/admin").hasRole("ADMIN") // 需要 ADMIN 角色
.antMatchers("/config/normal").access("hasRole('ROLE_NORMAL')") // 需要 NORMAL 角色。
.anyRequest().authenticated() // 任何请求,访问的用户都需要经过认证
.and()
.formLogin() // 设置 Form 表单登陆
// .loginPage("/login") // 登陆 URL 该地址这里可以自定义配置
.permitAll()
.and()
.logout() // 配置退出相关
// .logoutUrl("/logout") // 退出 URL 该地址这里可以自定义配置
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.
inMemoryAuthentication()// 使用内存中的 InMemoryUserDetailsManager
.passwordEncoder(NoOpPasswordEncoder.getInstance())// 不使用 PasswordEncoder 密码编码器
.withUser("admin").password("admin").roles("ADMIN") // 配置 admin 用户
.and().withUser("user").password("user").roles("NORMAL");// 配置 normal 用户
}
}
如上的注释已经解释和常规的配置什么含义, 下边是总结:
当配置了上述的 WebSecurityConfigurerAdapter Java的配置类之后,我们的应用便具备了如下的功能:
除了“/”,”/home”(首页),”/login”(登录),”/logout”(注销)之外,其他路径都需要认证。
指定“/login”该路径为登录页面,当未认证的用户尝试访问任何受保护的资源时,都会跳转到“/login”。
默认指定“/logout”为注销页面
配置一个内存中的用户认证器,使用admin/admin作为用户名和密码,具有USER角色
防止CSRF攻击
还可以继续配置, 如下:
@Configuration
public class CustomWe