我遇到有关文件上传的安全问题。
如何将文件上载限制为特定用户角色?
我使用@PreAuthorize("hasRole('USER')")
,但它首先上传文件,然后检查角色。超过文件上载大小时尤其可以看到这一点。用户将获得超出异常的上传大小,而不是重定向到登录表单。
这就是我的控制器的样子:
@Controller
@PreAuthorize("hasRole('USER')")
@Secured("ROLE_USER") // added this just to see if it makes a difference, it doesn't
@RequestMapping(value = "/self/upload", produces = "application/json")
public class JsonUserSelfUpload {
...
@RequestMapping(value = "", method = RequestMethod.POST, consumes="multipart/form-data")
public ModelAndView fileUpload(
@RequestParam(value = "file", required = true) MultipartFile inputFile,
@RequestParam(value = "param1", defaultValue = "") String type,
HttpServletResponse response
) throws Exception {
...
}
}
任何人都知道如何保护文件上传到特定角色?
编辑,更具体一点: 如果用户未经过身份验证,我想拒绝上传。拒绝我的意思是,在上传实际完成之前关闭连接。不确定spring是否有能力这样做,或者我需要一个过滤器来拒绝上传(多部分)。
更新: 尝试过滤器也没有成功。 似乎没有办法关闭连接。 这就是我的过滤器的样子:
public class RestrictUploadFilter implements Filter{
@Override
public void init(FilterConfig arg0) throws ServletException {
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String contentType = request.getContentType();
if (HttpMethods.POST.equals(request.getMethod()) && contentType != null && contentType.toLowerCase().indexOf("multipart/form-data") > -1) {
UserSession session = SpringHelper.getUserSession();
if (session != null && session.getRoles().contains(UserRole.USER)) {
// user is allowed to upload
chain.doFilter(req, res);
} else {
// access denied
response.setStatus(HttpStatus.FORBIDDEN_403);
response.setHeader("Connection", "close");
response.flushBuffer();
}
} else {
chain.doFilter(req, res);
}
}
}