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 9, 2024
1 parent b2c3a6b commit 33978af
Show file tree
Hide file tree
Showing 13 changed files with 124 additions and 122 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -63,95 +63,107 @@
@RequiredArgsConstructor
public class AuthorizationServerConfiguration {

private final OAuth2AuthorizationService authorizationService;

private final PasswordDecoderFilter passwordDecoderFilter;

private final ValidateCodeFilter validateCodeFilter;


@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
@ConditionalOnProperty(value = "security.micro", matchIfMissing = true)
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer();

// 增加验证码过滤器
http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class);
// 增加密码解密过滤器
http.addFilterBefore(passwordDecoderFilter, UsernamePasswordAuthenticationFilter.class);

http.with(authorizationServerConfigurer.tokenEndpoint((tokenEndpoint) -> {// 个性化认证授权端点
tokenEndpoint.accessTokenRequestConverter(accessTokenRequestConverter()) // 注入自定义的授权认证Converter
.accessTokenResponseHandler(new PigAuthenticationSuccessEventHandler()) // 登录成功处理器
.errorResponseHandler(new PigAuthenticationFailureEventHandler());// 登录失败处理器
}).clientAuthentication(oAuth2ClientAuthenticationConfigurer -> // 个性化客户端认证
oAuth2ClientAuthenticationConfigurer.errorResponseHandler(new PigAuthenticationFailureEventHandler()))// 处理客户端认证异常
.authorizationEndpoint(authorizationEndpoint -> authorizationEndpoint// 授权码端点个性化confirm页面
.consentPage(SecurityConstants.CUSTOM_CONSENT_PAGE_URI)), Customizer.withDefaults());

AntPathRequestMatcher[] requestMatchers = new AntPathRequestMatcher[]{AntPathRequestMatcher.antMatcher("/token/**"), AntPathRequestMatcher.antMatcher("/actuator/**"), AntPathRequestMatcher.antMatcher("/code/image"), AntPathRequestMatcher.antMatcher("/css/**"), AntPathRequestMatcher.antMatcher("/error")};

http.authorizeHttpRequests(authorizeRequests -> {
// 自定义接口、端点暴露
authorizeRequests.requestMatchers(requestMatchers).permitAll();
authorizeRequests.anyRequest().authenticated();
}).with(authorizationServerConfigurer.authorizationService(authorizationService)// redis存储token的实现
.authorizationServerSettings(AuthorizationServerSettings.builder().issuer(SecurityConstants.PROJECT_LICENSE).build()), Customizer.withDefaults());
http.with(new FormIdentityLoginConfigurer(), Customizer.withDefaults());
DefaultSecurityFilterChain securityFilterChain = http.build();

// 注入自定义授权模式实现
addCustomOAuth2GrantAuthenticationProvider(http);

return securityFilterChain;
}

/**
* 令牌生成规则实现 </br>
* client:username:uuid
*
* @return OAuth2TokenGenerator
*/
@Bean
public OAuth2TokenGenerator oAuth2TokenGenerator() {
CustomeOAuth2AccessTokenGenerator accessTokenGenerator = new CustomeOAuth2AccessTokenGenerator();
// 注入Token 增加关联用户信息
accessTokenGenerator.setAccessTokenCustomizer(new CustomeOAuth2TokenCustomizer());
return new DelegatingOAuth2TokenGenerator(accessTokenGenerator, new OAuth2RefreshTokenGenerator());
}

/**
* request -> xToken 注入请求转换器
*
* @return DelegatingAuthenticationConverter
*/
@Bean
public AuthenticationConverter accessTokenRequestConverter() {
return new DelegatingAuthenticationConverter(Arrays.asList(new OAuth2ResourceOwnerPasswordAuthenticationConverter(), new OAuth2ResourceOwnerSmsAuthenticationConverter(), new OAuth2RefreshTokenAuthenticationConverter(), new OAuth2ClientCredentialsAuthenticationConverter(), new OAuth2AuthorizationCodeAuthenticationConverter(), new OAuth2AuthorizationCodeRequestAuthenticationConverter()));
}

/**
* 注入授权模式实现提供方
* <p>
* 1. 密码模式 </br>
* 2. 短信登录 </br>
*/
@SuppressWarnings("unchecked")
private void addCustomOAuth2GrantAuthenticationProvider(HttpSecurity http) {
AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
OAuth2AuthorizationService authorizationService = http.getSharedObject(OAuth2AuthorizationService.class);

OAuth2ResourceOwnerPasswordAuthenticationProvider resourceOwnerPasswordAuthenticationProvider = new OAuth2ResourceOwnerPasswordAuthenticationProvider(authenticationManager, authorizationService, oAuth2TokenGenerator());

OAuth2ResourceOwnerSmsAuthenticationProvider resourceOwnerSmsAuthenticationProvider = new OAuth2ResourceOwnerSmsAuthenticationProvider(authenticationManager, authorizationService, oAuth2TokenGenerator());

// 处理 UsernamePasswordAuthenticationToken
http.authenticationProvider(new PigDaoAuthenticationProvider());
// 处理 OAuth2ResourceOwnerPasswordAuthenticationToken
http.authenticationProvider(resourceOwnerPasswordAuthenticationProvider);
// 处理 OAuth2ResourceOwnerSmsAuthenticationToken
http.authenticationProvider(resourceOwnerSmsAuthenticationProvider);
}
private final OAuth2AuthorizationService authorizationService;

private final PasswordDecoderFilter passwordDecoderFilter;

private final ValidateCodeFilter validateCodeFilter;

@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
@ConditionalOnProperty(value = "security.micro", matchIfMissing = true)
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer();

// 增加验证码过滤器
http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class);
// 增加密码解密过滤器
http.addFilterBefore(passwordDecoderFilter, UsernamePasswordAuthenticationFilter.class);

http.with(authorizationServerConfigurer.tokenEndpoint((tokenEndpoint) -> {// 个性化认证授权端点
tokenEndpoint.accessTokenRequestConverter(accessTokenRequestConverter()) // 注入自定义的授权认证Converter
.accessTokenResponseHandler(new PigAuthenticationSuccessEventHandler()) // 登录成功处理器
.errorResponseHandler(new PigAuthenticationFailureEventHandler());// 登录失败处理器
}).clientAuthentication(oAuth2ClientAuthenticationConfigurer -> // 个性化客户端认证
oAuth2ClientAuthenticationConfigurer.errorResponseHandler(new PigAuthenticationFailureEventHandler()))// 处理客户端认证异常
.authorizationEndpoint(authorizationEndpoint -> authorizationEndpoint// 授权码端点个性化confirm页面
.consentPage(SecurityConstants.CUSTOM_CONSENT_PAGE_URI)), Customizer.withDefaults());

AntPathRequestMatcher[] requestMatchers = new AntPathRequestMatcher[]{
AntPathRequestMatcher.antMatcher("/token/**"), AntPathRequestMatcher.antMatcher("/actuator/**"),
AntPathRequestMatcher.antMatcher("/code/image"), AntPathRequestMatcher.antMatcher("/css/**"),
AntPathRequestMatcher.antMatcher("/error")};

http.authorizeHttpRequests(authorizeRequests -> {
// 自定义接口、端点暴露
authorizeRequests.requestMatchers(requestMatchers).permitAll();
authorizeRequests.anyRequest().authenticated();
})
.with(authorizationServerConfigurer.authorizationService(authorizationService)// redis存储token的实现
.authorizationServerSettings(
AuthorizationServerSettings.builder().issuer(SecurityConstants.PROJECT_LICENSE).build()),
Customizer.withDefaults());
http.with(new FormIdentityLoginConfigurer(), Customizer.withDefaults());
DefaultSecurityFilterChain securityFilterChain = http.build();

// 注入自定义授权模式实现
addCustomOAuth2GrantAuthenticationProvider(http);

return securityFilterChain;
}

/**
* 令牌生成规则实现 </br>
* client:username:uuid
*
* @return OAuth2TokenGenerator
*/
@Bean
public OAuth2TokenGenerator oAuth2TokenGenerator() {
CustomeOAuth2AccessTokenGenerator accessTokenGenerator = new CustomeOAuth2AccessTokenGenerator();
// 注入Token 增加关联用户信息
accessTokenGenerator.setAccessTokenCustomizer(new CustomeOAuth2TokenCustomizer());
return new DelegatingOAuth2TokenGenerator(accessTokenGenerator, new OAuth2RefreshTokenGenerator());
}

/**
* request -> xToken 注入请求转换器
*
* @return DelegatingAuthenticationConverter
*/
@Bean
public AuthenticationConverter accessTokenRequestConverter() {
return new DelegatingAuthenticationConverter(Arrays.asList(
new OAuth2ResourceOwnerPasswordAuthenticationConverter(),
new OAuth2ResourceOwnerSmsAuthenticationConverter(), new OAuth2RefreshTokenAuthenticationConverter(),
new OAuth2ClientCredentialsAuthenticationConverter(),
new OAuth2AuthorizationCodeAuthenticationConverter(),
new OAuth2AuthorizationCodeRequestAuthenticationConverter()));
}

/**
* 注入授权模式实现提供方
* <p>
* 1. 密码模式 </br>
* 2. 短信登录 </br>
*/
@SuppressWarnings("unchecked")
private void addCustomOAuth2GrantAuthenticationProvider(HttpSecurity http) {
AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
OAuth2AuthorizationService authorizationService = http.getSharedObject(OAuth2AuthorizationService.class);

OAuth2ResourceOwnerPasswordAuthenticationProvider resourceOwnerPasswordAuthenticationProvider = new OAuth2ResourceOwnerPasswordAuthenticationProvider(
authenticationManager, authorizationService, oAuth2TokenGenerator());

OAuth2ResourceOwnerSmsAuthenticationProvider resourceOwnerSmsAuthenticationProvider = new OAuth2ResourceOwnerSmsAuthenticationProvider(
authenticationManager, authorizationService, oAuth2TokenGenerator());

// 处理 UsernamePasswordAuthenticationToken
http.authenticationProvider(new PigDaoAuthenticationProvider());
// 处理 OAuth2ResourceOwnerPasswordAuthenticationToken
http.authenticationProvider(resourceOwnerPasswordAuthenticationProvider);
// 处理 OAuth2ResourceOwnerSmsAuthenticationToken
http.authenticationProvider(resourceOwnerSmsAuthenticationProvider);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,6 @@ public void image(String randomStr, HttpServletResponse response) {
.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 @@ -231,9 +231,9 @@ public R<Page> tokenList(@RequestBody Map<String, Object> params) {
tokenVo.setIssuedAt(issuedAt);
return tokenVo;
}).collect(Collectors.toList());
result.setRecords(tokenVoList);
result.setTotal(keys.size());
return R.ok(result);
}
result.setRecords(tokenVoList);
result.setTotal(keys.size());
return R.ok(result);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,14 @@ public class PasswordDecoderFilter extends OncePerRequestFilter {

private static final String KEY_ALGORITHM = "AES";


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

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
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);
Expand All @@ -76,7 +76,6 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
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)) {
Expand All @@ -90,5 +89,4 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
chain.doFilter(requestWrapper, response);
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
* @date 2024/4/3
*/


import cn.hutool.core.util.StrUtil;
import com.pig4cloud.pig.common.core.constant.CacheConstants;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
Expand Down Expand Up @@ -42,9 +41,9 @@ public class ValidateCodeFilter extends OncePerRequestFilter {

private final AuthSecurityConfigProperties authSecurityConfigProperties;


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

String requestUrl = request.getServletPath();

Expand Down Expand Up @@ -120,7 +119,6 @@ private void checkCode() throws ValidateCodeException {
}

redisTemplate.delete(key);
}
}

}

Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
* @author lengleng
* 单体版本启动器,只需要运行此模块则整个系统启动
* @author lengleng 单体版本启动器,只需要运行此模块则整个系统启动
*/
@EnablePigDoc(value = "admin", isMicro = false)
@EnablePigResourceServer
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,7 @@
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

/**
* @author lengleng
* 认证授权服务器配置
* @author lengleng 认证授权服务器配置
*/
@Configuration
@RequiredArgsConstructor
Expand All @@ -77,7 +76,6 @@ public class PigBootSecurityServerConfiguration {

private final PermitAllUrlProperties permitAllUrl;


@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
Expand Down Expand Up @@ -132,7 +130,6 @@ public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity h
return securityFilterChain;
}


/**
* 注入授权模式实现提供方
* <p>
Expand All @@ -156,6 +153,6 @@ private void addCustomOAuth2GrantAuthenticationProvider(HttpSecurity http) {
http.authenticationProvider(resourceOwnerPasswordAuthenticationProvider);
// 处理 OAuth2ResourceOwnerSmsAuthenticationToken
http.authenticationProvider(resourceOwnerSmsAuthenticationProvider);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,6 @@ private void registerClientConfiguration(BeanDefinitionRegistry registry, Object
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ public void afterPropertiesSet() throws Exception {
return;
}


ServiceInstance serviceInstance = applicationContext.getBean(ServiceInstance.class);
serviceInstance.getMetadata().put("spring-doc", path);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
@Configuration(proxyBeanMethods = false)
public class GatewayConfiguration {


/**
* 创建PigRequest全局过滤器
* @return PigRequest全局过滤器
Expand All @@ -24,7 +23,6 @@ public PigRequestGlobalFilter pigRequestGlobalFilter() {
return new PigRequestGlobalFilter();
}


/**
* 创建全局异常处理程序
* @param objectMapper 对象映射器
Expand All @@ -35,5 +33,4 @@ public GlobalExceptionHandler globalExceptionHandler(ObjectMapper objectMapper)
return new GlobalExceptionHandler(objectMapper);
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ public R save(@Valid @RequestBody SysLog sysLog) {
@GetMapping("/export")
@PreAuthorize("@pms.hasPermission('sys_log_export')")
public List<SysLog> export(SysLogDTO sysLog) {
return sysLogService.getList(sysLog);
}
return sysLogService.getList(sysLog);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -59,5 +59,6 @@ public interface SysLogService extends IService<SysLog> {
* @param sysLog 查询条件
* @return List<SysLog>
*/
List<SysLog> getList(SysLogDTO sysLog);
List<SysLog> getList(SysLogDTO sysLog);

}
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,9 @@ private LambdaQueryWrapper buildQuery(SysLogDTO sysLog) {
if (ArrayUtil.isNotEmpty(sysLog.getCreateTime())) {
wrapper.ge(SysLog::getCreateTime, sysLog.getCreateTime()[0])
.le(SysLog::getCreateTime, sysLog.getCreateTime()[1]);
}
}

return wrapper;
}

return wrapper;
}
}

0 comments on commit 33978af

Please sign in to comment.