目录
基于角色和权限进行访问控制
第一个方法: hasAuthority 方法,如果当前的主体具有指定的权限,则返回 true,否则返回 false
1)在配置类中设置当前的路径有哪些权限才可以访问
.antMatchers("/test/index").hasAuthority("admin")
2)给用户设置这个权限
在userDetailService实现类中,给返回的user加上权限,如下:
List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("admins");
第二个方法:hasAnyAuthority 方法,如果当前的主体有任何提供的角色(给定的作为一个逗号分隔的字符串列表)的话,返回true。
只要有多个权限中的任意一个就可以,配置方式如下:
.antMatchers("/test/index").hasAnyAuthority("admin", "root")
第三个方法:hasRole 方法,如果用户具备给定角色就允许访问,否则出现 403。如果当前主体具有指定的角色,则返回 true。
1)配置文件修改
.antMatchers("/test/index").hasRole("teacher")
2)在userDetailService中给返回的用户加上角色teacher,注意在源码中,角色前缀有一个ROLE_,所有在给用户角色的时候要变成ROLE_teacher,如下:
List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("root,ROLE_teacher");
第四个方法:hasAnyRole,表示用户具备任何一个条件都可以访问。
1)角色配置
.antMatchers("/test/index").hasAnyRole("stu","sale")
2)用户角色设置
List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("root,ROLE_sale");
自定义403没有权限访问的页面
1)新建无权限访问的自定义页面
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>你无权访问!!</h1>
</body>
</html>
2)在配置类中配置