Skip to content

Commit

Permalink
🎨 Improving structure / format of the code.
Browse files Browse the repository at this point in the history
  • Loading branch information
lltx committed Apr 17, 2024
1 parent 22e33cf commit e7a20be
Show file tree
Hide file tree
Showing 16 changed files with 817 additions and 828 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,14 @@ public class WebSecurityConfiguration {
@Bean
SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
http.authorizeRequests(authorizeRequests -> authorizeRequests.antMatchers("/token/*")
.permitAll()// 开放自定义的部分端点
.anyRequest()
.authenticated())
.headers()
.frameOptions()
.sameOrigin()// 避免iframe同源无法登录
.and()
.apply(new FormIdentityLoginConfigurer()); // 表单登录个性化
.permitAll()// 开放自定义的部分端点
.anyRequest()
.authenticated())
.headers()
.frameOptions()
.sameOrigin()// 避免iframe同源无法登录
.and()
.apply(new FormIdentityLoginConfigurer()); // 表单登录个性化
// 处理 UsernamePasswordAuthenticationToken
http.authenticationProvider(new PigDaoAuthenticationProvider());
return http.build();
Expand All @@ -67,13 +67,13 @@ SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Excepti
@Order(0)
SecurityFilterChain resources(HttpSecurity http) throws Exception {
http.requestMatchers((matchers) -> matchers.antMatchers("/actuator/**", "/code/image", "/css/**", "/error"))
.authorizeHttpRequests((authorize) -> authorize.anyRequest().permitAll())
.requestCache()
.disable()
.securityContext()
.disable()
.sessionManagement()
.disable();
.authorizeHttpRequests((authorize) -> authorize.anyRequest().permitAll())
.requestCache()
.disable()
.securityContext()
.disable()
.sessionManagement()
.disable();
return http.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,25 +24,25 @@
@RequiredArgsConstructor
public class ImageCodeEndpoint {

private static final Integer DEFAULT_IMAGE_WIDTH = 100;
private static final Integer DEFAULT_IMAGE_WIDTH = 100;

private static final Integer DEFAULT_IMAGE_HEIGHT = 40;
private static final Integer DEFAULT_IMAGE_HEIGHT = 40;

private final StringRedisTemplate redisTemplate;
private final StringRedisTemplate redisTemplate;

/**
* 创建图形验证码
*/
@SneakyThrows
@GetMapping("/image")
public void image(String randomStr, HttpServletResponse response) {
ArithmeticCaptcha captcha = new ArithmeticCaptcha(DEFAULT_IMAGE_WIDTH, DEFAULT_IMAGE_HEIGHT);
/**
* 创建图形验证码
*/
@SneakyThrows
@GetMapping("/image")
public void image(String randomStr, HttpServletResponse response) {
ArithmeticCaptcha captcha = new ArithmeticCaptcha(DEFAULT_IMAGE_WIDTH, DEFAULT_IMAGE_HEIGHT);

String result = captcha.text();
redisTemplate.opsForValue()
.set(CacheConstants.DEFAULT_CODE_KEY + randomStr, result, SecurityConstants.CODE_TIME, TimeUnit.SECONDS);
// 转换流信息写出
captcha.out(response.getOutputStream());
String result = captcha.text();
redisTemplate.opsForValue()
.set(CacheConstants.DEFAULT_CODE_KEY + randomStr, result, SecurityConstants.CODE_TIME, TimeUnit.SECONDS);
// 转换流信息写出
captcha.out(response.getOutputStream());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -47,46 +47,46 @@
@RequiredArgsConstructor
public class PasswordDecoderFilter extends OncePerRequestFilter {

private final AuthSecurityConfigProperties authSecurityConfigProperties;
private final AuthSecurityConfigProperties authSecurityConfigProperties;

private static final String PASSWORD = "password";
private static final String PASSWORD = "password";

private static final String KEY_ALGORITHM = "AES";
private static final String KEY_ALGORITHM = "AES";

static {
// 关闭hutool 强制关闭Bouncy Castle库的依赖
SecureUtil.disableBouncyCastle();
}
static {
// 关闭hutool 强制关闭Bouncy Castle库的依赖
SecureUtil.disableBouncyCastle();
}

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
// 不是登录请求,直接向下执行
if (!StrUtil.containsAnyIgnoreCase(request.getRequestURI(), SecurityConstants.OAUTH_TOKEN_URL)) {
chain.doFilter(request, response);
return;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
// 不是登录请求,直接向下执行
if (!StrUtil.containsAnyIgnoreCase(request.getRequestURI(), SecurityConstants.OAUTH_TOKEN_URL)) {
chain.doFilter(request, response);
return;
}

// 将请求流转换为可多次读取的请求流
RepeatBodyRequestWrapper requestWrapper = new RepeatBodyRequestWrapper(request);
Map<String, String[]> parameterMap = requestWrapper.getParameterMap();
// 将请求流转换为可多次读取的请求流
RepeatBodyRequestWrapper requestWrapper = new RepeatBodyRequestWrapper(request);
Map<String, String[]> parameterMap = requestWrapper.getParameterMap();

// 构建前端对应解密AES 因子
AES aes = new AES(Mode.CFB, Padding.NoPadding,
new SecretKeySpec(authSecurityConfigProperties.getEncodeKey().getBytes(), KEY_ALGORITHM),
new IvParameterSpec(authSecurityConfigProperties.getEncodeKey().getBytes()));
// 构建前端对应解密AES 因子
AES aes = new AES(Mode.CFB, Padding.NoPadding,
new SecretKeySpec(authSecurityConfigProperties.getEncodeKey().getBytes(), KEY_ALGORITHM),
new IvParameterSpec(authSecurityConfigProperties.getEncodeKey().getBytes()));

parameterMap.forEach((k, v) -> {
String[] values = parameterMap.get(k);
if (!PASSWORD.equals(k) || ArrayUtil.isEmpty(values)) {
return;
}
parameterMap.forEach((k, v) -> {
String[] values = parameterMap.get(k);
if (!PASSWORD.equals(k) || ArrayUtil.isEmpty(values)) {
return;
}

// 解密密码
String decryptPassword = aes.decryptStr(values[0]);
parameterMap.put(k, new String[]{decryptPassword});
});
chain.doFilter(requestWrapper, response);
}
// 解密密码
String decryptPassword = aes.decryptStr(values[0]);
parameterMap.put(k, new String[] { decryptPassword });
});
chain.doFilter(requestWrapper, response);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -40,86 +40,87 @@
@RequiredArgsConstructor
public class ValidateCodeFilter extends OncePerRequestFilter {

private final AuthSecurityConfigProperties authSecurityConfigProperties;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {

String requestUrl = request.getServletPath();

// 不是登录URL 请求直接跳过
if (!SecurityConstants.OAUTH_TOKEN_URL.equals(requestUrl)) {
filterChain.doFilter(request, response);
return;
}

// 如果登录URL 但是刷新token的请求,直接向下执行
String grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE);
if (StrUtil.equals(SecurityConstants.REFRESH_TOKEN, grantType)) {
filterChain.doFilter(request, response);
return;
}

// 客户端配置跳过验证码
boolean isIgnoreClient = authSecurityConfigProperties.getIgnoreClients().contains(WebUtils.getClientId());
if (isIgnoreClient) {
filterChain.doFilter(request, response);
return;
}

// 校验验证码 1. 客户端开启验证码 2. 短信模式
try {
checkCode();
filterChain.doFilter(request, response);
} catch (ValidateCodeException validateCodeException) {
throw new OAuth2AuthenticationException(validateCodeException.getMessage());
}
}

/**
* 校验验证码
*/
private void checkCode() throws ValidateCodeException {
Optional<HttpServletRequest> request = WebUtils.getRequest();
String code = request.get().getParameter("code");

if (StrUtil.isBlank(code)) {
throw new ValidateCodeException("验证码不能为空");
}

String randomStr = request.get().getParameter("randomStr");

// https://gitee.com/log4j/pig/issues/IWA0D
String mobile = request.get().getParameter("mobile");
if (StrUtil.isNotBlank(mobile)) {
randomStr = mobile;
}

String key = CacheConstants.DEFAULT_CODE_KEY + randomStr;
RedisTemplate<String, String> redisTemplate = SpringContextHolder.getBean(StringRedisTemplate.class);
if (Boolean.FALSE.equals(redisTemplate.hasKey(key))) {
throw new ValidateCodeException("验证码不合法");
}

Object codeObj = redisTemplate.opsForValue().get(key);

if (codeObj == null) {
throw new ValidateCodeException("验证码不合法");
}

String saveCode = codeObj.toString();
if (StrUtil.isBlank(saveCode)) {
redisTemplate.delete(key);
throw new ValidateCodeException("验证码不合法");
}

if (!StrUtil.equals(saveCode, code)) {
redisTemplate.delete(key);
throw new ValidateCodeException("验证码不合法");
}

redisTemplate.delete(key);
private final AuthSecurityConfigProperties authSecurityConfigProperties;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {

String requestUrl = request.getServletPath();

// 不是登录URL 请求直接跳过
if (!SecurityConstants.OAUTH_TOKEN_URL.equals(requestUrl)) {
filterChain.doFilter(request, response);
return;
}

// 如果登录URL 但是刷新token的请求,直接向下执行
String grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE);
if (StrUtil.equals(SecurityConstants.REFRESH_TOKEN, grantType)) {
filterChain.doFilter(request, response);
return;
}

// 客户端配置跳过验证码
boolean isIgnoreClient = authSecurityConfigProperties.getIgnoreClients().contains(WebUtils.getClientId());
if (isIgnoreClient) {
filterChain.doFilter(request, response);
return;
}

// 校验验证码 1. 客户端开启验证码 2. 短信模式
try {
checkCode();
filterChain.doFilter(request, response);
}
catch (ValidateCodeException validateCodeException) {
throw new OAuth2AuthenticationException(validateCodeException.getMessage());
}
}

/**
* 校验验证码
*/
private void checkCode() throws ValidateCodeException {
Optional<HttpServletRequest> request = WebUtils.getRequest();
String code = request.get().getParameter("code");

if (StrUtil.isBlank(code)) {
throw new ValidateCodeException("验证码不能为空");
}

String randomStr = request.get().getParameter("randomStr");

// https://gitee.com/log4j/pig/issues/IWA0D
String mobile = request.get().getParameter("mobile");
if (StrUtil.isNotBlank(mobile)) {
randomStr = mobile;
}

String key = CacheConstants.DEFAULT_CODE_KEY + randomStr;
RedisTemplate<String, String> redisTemplate = SpringContextHolder.getBean(StringRedisTemplate.class);
if (Boolean.FALSE.equals(redisTemplate.hasKey(key))) {
throw new ValidateCodeException("验证码不合法");
}

Object codeObj = redisTemplate.opsForValue().get(key);

if (codeObj == null) {
throw new ValidateCodeException("验证码不合法");
}

String saveCode = codeObj.toString();
if (StrUtil.isBlank(saveCode)) {
redisTemplate.delete(key);
throw new ValidateCodeException("验证码不合法");
}

if (!StrUtil.equals(saveCode, code)) {
redisTemplate.delete(key);
throw new ValidateCodeException("验证码不合法");
}

redisTemplate.delete(key);
}

}
Loading

0 comments on commit e7a20be

Please sign in to comment.