- 准备工作
创建一个springBoot项目,解压附件java压缩包将对应的文件分别放到
2. 引入依赖
<!--security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!--security-->
3.创建security配置类
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
//定义授权规则
@Override
protected void configure(HttpSecurity http) throws Exception {
//访问/任意角色 访问/level1下的所有角色必须要有权限VIP1
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("VIP1")
.antMatchers("/level2/**").hasRole("VIP2")
.antMatchers("/level3/**").hasRole("VIP3");
//开启自动配置的登录页 user和pwd 为登录页上的用户名和密码的参数名
http.formLogin().usernameParameter("user").passwordParameter("pwd").loginPage("/userlogin");
// //1. /login请求来到登录页
// //2. 重定向/login?error表示登陆失败
//
// //注销成功后来到/
http.logout();
//1. 访问/logout 表示用户会注销,清空sessin
//2. 注销成功后会返回 /login?logout页面
//开启记住我功能 remeber为登录页上的记住我参数名
http.rememberMe().rememberMeParameter("remeber");
}
//定义认证规则
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1","VIP2")
.and()
.withUser("lisi").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP2","VIP3")
.and()
.withUser("wangwu").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1","VIP3");
}
}
附上源码: