spring security 控制授权
2019-09-17 本文已影响0人
yunqing_71
一个业务系统,一个管理系统:

两方面:
1.控制访问的url需要什么权限
2.控制用户拥有什么权限

①下面来看只需要控制是否登陆:

就是这块代码控制,这些给出的url不需要登录,剩下的都需要登录。
②只区分简单角色的情况:

如下图所示:可以指定user/*的Get请求需要Admin权限:


AnonymousAuthenticationFilter.class
这个匿名认证过滤器位于所有绿色过滤器之后:
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
/**
判断是否有认证信息,没有则创建一个
*/
if (SecurityContextHolder.getContext().getAuthentication() == null) {
SecurityContextHolder.getContext().setAuthentication(
createAuthentication((HttpServletRequest) req));
if (logger.isDebugEnabled()) {
logger.debug("Populated SecurityContextHolder with anonymous token: '"
+ SecurityContextHolder.getContext().getAuthentication() + "'");
}
}
else {
if (logger.isDebugEnabled()) {
logger.debug("SecurityContextHolder not populated with anonymous token, as it already contained: '"
+ SecurityContextHolder.getContext().getAuthentication() + "'");
}
}
chain.doFilter(req, res);
}
/**
创建认证信息就算没有认证信息,都会创建一个字符串,看principal中如下图:
*/
protected Authentication createAuthentication(HttpServletRequest request) {
AnonymousAuthenticationToken auth = new AnonymousAuthenticationToken(key,
principal, authorities);
auth.setDetails(authenticationDetailsSource.buildDetails(request));
return auth;
}


权限表达式:
这些权限表达式都是跟在antMatchers()之后的,每个权限表达式对应一个方法例如:permitAll()返回true,就是所有的都通过。

权限表达式连起来用,需要这样使用:

也可以自定义权限表达式:
RBAC数据模型:
一般来说5张表:用户表,角色表,资源表,用户角色表,角色资源表
