spring boot —— Spring Security定制权限管理
前言
Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。提供了完善的认证机制和方法级的授权功能。是一款非常优秀的权限管理框架。它的核心是一组过滤。
类似于Shiro
启动spring boot项目后,会先验证,如果没有登陆,会跳转到框架默认登录页面(封装好的,不用自己写)
如果没有配置登录用户,那么终端会自动生成用户并打印随机生成的用户密码,如果有配置,就不会生成。
Spring Security的使用
1、pom文件导依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2、Spring Security的xml配置文件基本内容:
spring.security.user.name=test
spring.security.user.password=123456
spring.security.user.roles[0]=user
spring.security.user.roles[1]=admin
3、控制类
Spring Security控制器
@Controller
public class TestControoller {
@RequestMapping("/index")
@ResponseBody
public String index(){
return "index页面";
}
}
项目逻辑控制器
@Controller
public class TestControoller {
@RequestMapping("/index")
@ResponseBody
public String index(){
return "欢迎访问";
}
}
4、实现类
// 让所有用户都有访问的权限
.antMatchers().permitAll()
// 授予用户权限,对应xml文件里的roles的
.anyRequest().hasRole("user")
@Configuration
public class SecurityConfigration extends WebSecurityConfigurerAdapter
{
@Override
protected void configure(HttpSecurity http) throws Exception{
http
.authorizeHttpRequests()
.antMatchers().permitAll()
.anyRequest().hasRole("user")
.and()
.formLogin();
}
}
运行过程:
访问:http://localhost:8080/index,会跳转http://localhost:8080/login,输入在xml配置文件内容
点击登陆后,跳转index页面显示“index页面”
其他: