Spring Security权限认证规则
1、当服务器启动时,Spring Security会根据配置将所有的URL和其对应的权限加载到Spring Security中。
@Service
public class MyInvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource {
@Autowired
private T_permissionMapper permissionMapper;
private HashMap<String, Collection<ConfigAttribute>> map =null;
/**
* 加载权限表中所有权限
*/
public void loadResourceDefine(){
map = new HashMap<>();
Collection<ConfigAttribute> array;
ConfigAttribute cfg;
// 从数据库中查询所有权限信息
List<T_permission> permissions = permissionMapper.findAll();
for(T_permission permission : permissions) {
array = new ArrayList<>();
cfg = new SecurityConfig(permission.getPerms());
array.add(cfg);
// 将查询到的url作为key,将封装了权限标志的SecurityConfig对象集合作为value
map.put(permission.getUrl(), array);
}
}
/**
* 判定用户请求的url是否在权限表中
*/
@Override
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
if(map == null) loadResourceDefine();
HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
AntPathRequestMatcher matcher;
String resUrl;
for(Iterator<String> iter = map.keySet().iterator(); iter.hasNext(); ) {
resUrl = iter.next();
matcher = new AntPathRequestMatcher(resUrl);
if(matcher.matches(request)) {
return map.get(resUrl);
}
}
return null;
}
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}
@Override
public boolean supports(Class<?> class1) {
return true;
}
}
2、当发起一个请求时,Spring Security会判断该请求url地址是否需要进行权限验证,如果不需要,那么直接访问。
3、如果这个URL需要进行权限验证,那么Spring Security会检查当前请求来源所属用户是否登录,如果没有登录,则跳转到登录页面,进行登录操作。
4、如果登录,那么判断这个用户所拥有的权限是否包含访问这个URL所需要的权限,如果有则允许访问
如果没有则会报500错误,提示:未在SecurityContext中查找到认证对象
5、如果没有权限,则会提示信息403