
1.引入spring-boot-starter-security依赖
2.编写SpringSecurity配置类
2.1 定制请求的授权规则
2.2 开启自动配置的登录功能(/login来到登录页;重庆向到/login?error表示登录失败)
2.3 开启自动配置的注销功能(访问/logout请求,表示用户注销并清空session;注销成功返回/login?logout)
2.4 开启自动配置的记住密码功能(http.rememberMe();)-登录成功以后,将Cookie发送给浏览器保存,可以实现记住密码功能;点击注销会删除Cookie,就没有记住密码功能
默认post形式的/login代表处理登录
2.5定义认证规则
@EnableSecurity
public class MySecurityConfig extends WebSecurityConfigureAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception{
// 定制请求的授权规则
http.authorizeRequest().antMatches("/").permitAll()
.antMatches("/level/**").hasRole("VIP");
// 开启自动配置的登录功能,如果没有权限就会跳转到登录页面
http.formLogin().loginPage("/"); // 跳转到自定义登录页
http.logout().logoutSuccessUrl("/"); // 注销成功返回首页
http.rememberMe().rememberMeParameter("remember"); // 开启自动配置的记住密码功能
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
auth.inMemoryAuthentication().withUser("username").password("password").roles("role1","role2")
.and()
.withUser("username").password("password").roles("role1","role2")
}
3.控制请求的访问权限