添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
设置简单权限问题
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;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//请求授权规则
@Override
protected void configure(HttpSecurity http) throws Exception {
// 首页所有人可以访问,功能页只有对应有权限的人才能访问
// /表示首页,首页所有人都能访问,所以是permitAll
// level1只能是VIP1可以访问
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
// 没有权限默认会到登录页面
http.formLogin();
// 注销用户,默认跳到登录界面
// http.logout();
//但是可以指定跳转位置,这里设置跳转到开始页面
http.logout().logoutSuccessUrl("/");
}
//认证规则
// 在springboot 2.1.X可以直接使用passwordEncoder("123456")
// 但是现在版本更新,需要用到passwordEncoder(new BCryptPasswordEncoder())密码编码
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("kuangshen").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
}
首页界面
若使用kuangshen登录,则只能进level1和level2,level3会报错
这里再额外说一个权限控制的问题,但是他跟springBoot的版本有关
我们现在的版本都比较新,这个权限控制好像是只能是旧版本,2.0.7/9都可以,这个权限控制就是用户是vip几的时候,就只显示几的菜单,不显示该用户没有权限的菜单,实现菜单动态化,想实现这个功能的话要先把springboot 的版本降下来
然后导入security和thyemleaf的整合包
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
这样我们在写html就可以加上security的判断,当这个用户属于vip1的时候,这段标签才会有作用