优化代码,支持防盗链功能

This commit is contained in:
2025-09-20 21:19:02 +08:00
parent 616e257617
commit 1b140fcc83
8 changed files with 530 additions and 481 deletions

View File

@@ -1,16 +1,19 @@
package com.devttl.framework.config;
import java.util.HashMap;
import java.util.Map;
import com.devttl.common.constant.Constants;
import com.devttl.common.filter.RefererFilter;
import com.devttl.common.filter.RepeatableFilter;
import com.devttl.common.filter.XssFilter;
import com.devttl.common.utils.StringUtils;
import jakarta.servlet.DispatcherType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.devttl.common.filter.RepeatableFilter;
import com.devttl.common.filter.XssFilter;
import com.devttl.common.utils.StringUtils;
import java.util.HashMap;
import java.util.Map;
/**
* Filter配置
@@ -18,19 +21,20 @@ import com.devttl.common.utils.StringUtils;
* @author devttl
*/
@Configuration
public class FilterConfig
{
public class FilterConfig {
@Value("${xss.excludes}")
private String excludes;
@Value("${xss.urlPatterns}")
private String urlPatterns;
@SuppressWarnings({ "rawtypes", "unchecked" })
@Value("${referer.allowed-domains}")
private String allowedDomains;
@SuppressWarnings({"rawtypes", "unchecked"})
@Bean
@ConditionalOnProperty(value = "xss.enabled", havingValue = "true")
public FilterRegistrationBean xssFilterRegistration()
{
public FilterRegistrationBean xssFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setDispatcherTypes(DispatcherType.REQUEST);
registration.setFilter(new XssFilter());
@@ -43,10 +47,25 @@ public class FilterConfig
return registration;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@SuppressWarnings({"rawtypes", "unchecked"})
@Bean
public FilterRegistrationBean someFilterRegistration()
{
@ConditionalOnProperty(value = "referer.enabled", havingValue = "true")
public FilterRegistrationBean refererFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setDispatcherTypes(DispatcherType.REQUEST);
registration.setFilter(new RefererFilter());
registration.addUrlPatterns(Constants.RESOURCE_PREFIX + "/*");
registration.setName("refererFilter");
registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
Map<String, String> initParameters = new HashMap<String, String>();
initParameters.put("allowedDomains", allowedDomains);
registration.setInitParameters(initParameters);
return registration;
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Bean
public FilterRegistrationBean someFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new RepeatableFilter());
registration.addUrlPatterns("/*");

View File

@@ -1,24 +1,12 @@
package com.devttl.framework.web.service;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.devttl.common.constant.CacheConstants;
import com.devttl.common.constant.Constants;
import com.devttl.common.constant.UserConstants;
import com.devttl.common.core.domain.entity.SysUser;
import com.devttl.common.core.domain.model.LoginUser;
import com.devttl.common.core.redis.RedisCache;
import com.devttl.common.exception.ServiceException;
import com.devttl.common.exception.user.BlackListException;
import com.devttl.common.exception.user.CaptchaException;
import com.devttl.common.exception.user.CaptchaExpireException;
import com.devttl.common.exception.user.UserNotExistsException;
import com.devttl.common.exception.user.UserPasswordNotMatchException;
import com.devttl.common.exception.user.*;
import com.devttl.common.utils.DateUtils;
import com.devttl.common.utils.MessageUtils;
import com.devttl.common.utils.StringUtils;
@@ -28,15 +16,22 @@ import com.devttl.framework.manager.factory.AsyncFactory;
import com.devttl.framework.security.context.AuthenticationContextHolder;
import com.devttl.system.service.ISysConfigService;
import com.devttl.system.service.ISysUserService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
/**
* 登录校验方法
*
*
* @author devttl
*/
@Component
public class SysLoginService
{
public class SysLoginService {
@Autowired
private TokenService tokenService;
@@ -45,7 +40,7 @@ public class SysLoginService
@Autowired
private RedisCache redisCache;
@Autowired
private ISysUserService userService;
@@ -54,43 +49,34 @@ public class SysLoginService
/**
* 登录验证
*
*
* @param username 用户名
* @param password 密码
* @param code 验证码
* @param uuid 唯一标识
* @param code 验证码
* @param uuid 唯一标识
* @return 结果
*/
public String login(String username, String password, String code, String uuid)
{
public String login(String username, String password, String code, String uuid) {
// 验证码校验
validateCaptcha(username, code, uuid);
// 登录前置校验
loginPreCheck(username, password);
// 用户验证
Authentication authentication = null;
try
{
try {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
AuthenticationContextHolder.setContext(authenticationToken);
// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
authentication = authenticationManager.authenticate(authenticationToken);
}
catch (Exception e)
{
if (e instanceof BadCredentialsException)
{
} catch (Exception e) {
if (e instanceof BadCredentialsException) {
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
throw new UserPasswordNotMatchException();
}
else
{
} else {
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
throw new ServiceException(e.getMessage());
}
}
finally
{
} finally {
AuthenticationContextHolder.clearContext();
}
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
@@ -102,27 +88,23 @@ public class SysLoginService
/**
* 校验验证码
*
*
* @param username 用户名
* @param code 验证码
* @param uuid 唯一标识
* @param code 验证码
* @param uuid 唯一标识
* @return 结果
*/
public void validateCaptcha(String username, String code, String uuid)
{
public void validateCaptcha(String username, String code, String uuid) {
boolean captchaEnabled = configService.selectCaptchaEnabled();
if (captchaEnabled)
{
if (captchaEnabled) {
String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
String captcha = redisCache.getCacheObject(verifyKey);
if (captcha == null)
{
if (captcha == null) {
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
throw new CaptchaExpireException();
}
redisCache.deleteObject(verifyKey);
if (!code.equalsIgnoreCase(captcha))
{
if (!code.equalsIgnoreCase(captcha)) {
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
throw new CaptchaException();
}
@@ -131,35 +113,31 @@ public class SysLoginService
/**
* 登录前置校验
*
* @param username 用户名
* @param password 用户密码
*/
public void loginPreCheck(String username, String password)
{
public void loginPreCheck(String username, String password) {
// 用户名或密码为空 错误
if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
{
if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
throw new UserNotExistsException();
}
// 密码如果不在指定范围内 错误
if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
|| password.length() > UserConstants.PASSWORD_MAX_LENGTH)
{
|| password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
throw new UserPasswordNotMatchException();
}
// 用户名不在指定范围内 错误
if (username.length() < UserConstants.USERNAME_MIN_LENGTH
|| username.length() > UserConstants.USERNAME_MAX_LENGTH)
{
|| username.length() > UserConstants.USERNAME_MAX_LENGTH) {
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
throw new UserPasswordNotMatchException();
}
// IP黑名单校验
String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
{
if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
throw new BlackListException();
}
@@ -170,12 +148,7 @@ public class SysLoginService
*
* @param userId 用户ID
*/
public void recordLoginInfo(Long userId)
{
SysUser sysUser = new SysUser();
sysUser.setUserId(userId);
sysUser.setLoginIp(IpUtils.getIpAddr());
sysUser.setLoginDate(DateUtils.getNowDate());
userService.updateUserProfile(sysUser);
public void recordLoginInfo(Long userId) {
userService.updateLoginInfo(userId, IpUtils.getIpAddr(), DateUtils.getNowDate());
}
}