自定义springcloud防止XSS,CSRF,SQL攻击,详细代码
时间: 2024-03-25 15:39:25 浏览: 93
自定义防止XSS攻击:
可以使用过滤器Filter来对请求进行过滤,过滤掉恶意脚本。以下是一个简单的过滤器实现:
```java
@Component
public class XssFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
XssHttpServletRequestWrapper wrapper = new XssHttpServletRequestWrapper((HttpServletRequest) request);
chain.doFilter(wrapper, response);
}
@Override
public void destroy() {
}
public static class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
public XssHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
}
@Override
public String getParameter(String name) {
String value = super.getParameter(name);
if (value != null) {
value = HtmlUtils.htmlEscape(value, "UTF-8");
}
return value;
}
@Override
public String[] getParameterValues(String name) {
String[] values = super.getParameterValues(name);
if (values != null) {
for (int i = 0; i < values.length; i++) {
values[i] = HtmlUtils.htmlEscape(values[i], "UTF-8");
}
}
return values;
}
}
}
```
自定义防止CSRF攻击:
可以使用Token来防止CSRF攻击,以下是一个简单的Token生成和验证的工具类:
```java
@Component
public class CsrfTokenUtils {
private static final String CSRF_TOKEN = "csrf_token";
public String generateToken() {
String token = UUID.randomUUID().toString();
HttpSession session = getSession();
session.setAttribute(CSRF_TOKEN, token);
return token;
}
public boolean checkToken(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return false;
}
String sessionToken = (String) session.getAttribute(CSRF_TOKEN);
String requestToken = request.getParameter(CSRF_TOKEN);
return StringUtils.equals(sessionToken, requestToken);
}
private HttpSession getSession() {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
return request.getSession();
}
}
```
自定义防止SQL注入攻击:
可以使用Mybatis等ORM框架的参数化查询来防止SQL注入攻击。以下是一个简单的Mybatis的参数化查询示例:
```java
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE username = #{username} AND password = #{password}")
User selectByUsernameAndPassword(@Param("username") String username, @Param("password") String password);
}
```
以上是一些自定义防止XSS、CSRF、SQL注入攻击的常见方法,具体的代码实现需要参考具体的业务场景和技术框架。
阅读全文