源码下载
一、API安全机制-访问控制 API安全机制.png
访问控制
访问控制算是API业务层的安全策略,为了达到你有什么权限做什么事的目的。常见的访问控制策略有ACL和RBAC
- ACL:Access Control Lists
- 优点:简单易用,实现容易。
- 缺点:无法满足复杂的业务需求,不易后期维护管理
- RBAC:Role Based Access Control
- 优点:引入角色概念,易于后期的维护管理。
- 缺点:相交ACL,开发相对复杂
二、ACL
- RavenUser中添加permissions权限字段
/**
* 负责与数据库对应
*/
@Data
@Entity
@Table(name = "t_user")
public class RavenUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@Column(unique = true)
private String username;
private String password;
private String permissions;
public RavenUserInfo builderUserInfo() {
RavenUserInfo userInfo = new RavenUserInfo();
BeanUtils.copyProperties(this, userInfo);
return userInfo;
}
public boolean hasPermission(String method) {
boolean result = false;
if (StringUtils.equalsIgnoreCase("get", method)) {
// GET请求的用户必须要有 "r" 权限
result = StringUtils.contains(this.permissions, "r");
}
else {
// GET请求的用户必须要有 "w" 权限
result = StringUtils.contains(this.permissions, "w");
}
return result;
}
}
- ACL拦截器 RavenAclInterceptor
/**
* ACL权限拦截器
*/
@Component
public class RavenAclInterceptor extends HandlerInterceptorAdapter {
/**
* 请求前缀拦截处理
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
boolean result = true;
// 获取用户信息
RavenUser user = (RavenUser) request.getAttribute("user");
if (null == user) {
// 用户未认证
response.setContentType("text/plain");
response.getWriter().write("need authentication");
response.setStatus(HttpStatus.UNAUTHORIZED.value());
result = false;
}
else {
// 用户没有权限
String method = request.getMethod();
if (!user.hasPermission(method)) {
response.setContentType("text/plain");
response.getWriter().write("forbidden");
response.setStatus(HttpStatus.FORBIDDEN.value());
result = false;
}
}
return result;
}
}
- 添加拦截器到链上
/**
* 拦截器配置类
*/
@Configuration
@EnableJpaAuditing
public class RavenInterceptorConfig implements WebMvcConfigurer {
/**
* 审核日志拦截器
*/
@Autowired
private RavenAuditLogInterceptor auditLogInterceptor;
/**
* ACL权限拦截器
*/
@Autowired
private RavenAclInterceptor aclInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
/**
* registry.addInterceptor(this.auditLogInterceptor).addPathPatterns("/user");
* 拦截器指定拦截的url
*
* 拦截器的添加顺序决定了拦截的先后顺序
*/
registry.addInterceptor(this.auditLogInterceptor);
registry.addInterceptor(this.aclInterceptor);
}
}
- 给用户Raven分配r权限 GET方法r权限.png
- 给用户Raven分配w权限时 GET方法只有w权限.png
- GET以外的其他请求也是如此
网友评论