Skip to content

Commit

Permalink
♻️ refactor(安全模块): 简化了代码并更新了依赖版本号,优化了性能
Browse files Browse the repository at this point in the history
  • Loading branch information
vnobo committed Jun 3, 2024
1 parent 3dd7a07 commit 234f9f4
Show file tree
Hide file tree
Showing 7 changed files with 29 additions and 60 deletions.
15 changes: 15 additions & 0 deletions boot/platform/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,21 @@ tasks.named("bootBuildImage") {
"-Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager"
]
publish = true
buildWorkspace {
bind {
source = "/tmp/cache-${rootProject.name}.work"
}
}
buildCache {
bind {
source = "/tmp/cache-${rootProject.name}.build"
}
}
launchCache {
bind {
source = "/tmp/cache-${rootProject.name}.launch"
}
}
docker {
publishRegistry {
username = "${dockerUsername}"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,86 +29,38 @@ public class SecurityController {
private final PasswordEncoder passwordEncoder;
private final ServerOAuth2AuthorizedClientRepository clientRepository;

/**
* This endpoint is used to generate an authentication token.
*
* @param session The current web session.
* @param authentication The authentication object containing the user's credentials.
* @return A Mono<AuthenticationToken> object containing the authentication token.
* &#064;GetMapping annotation is used to handle GET type requests. This endpoint is mapped to "/oauth2/token".
* The method uses the WebSession and Authentication parameters to build an AuthenticationToken.
* The building of the AuthenticationToken is deferred until subscription time to ensure that it is built with the most up-to-date session and authentication information.
* <p>
* The built AuthenticationToken is then wrapped in a Mono and returned.
*/
@GetMapping("token")
public Mono<AuthenticationToken> token(WebSession session, Authentication authentication) {
return Mono.defer(() -> Mono.just(AuthenticationToken.build(session, authentication)));
}

/**
* Retrieves the CSRF token from the current context.
*
* @return A Mono<CsrfToken> object containing the CSRF token, or an empty Mono if no CSRF token is found.
*/
@GetMapping("csrf")
public Mono<CsrfToken> csrfToken() {
// Defer the retrieval of the CSRF token to subscription time.
// This allows the CSRF token to be retrieved from the current context when the Mono is subscribed to.
return Mono.deferContextual((contextView) -> {
// Retrieve the CSRF token from the current context.
CsrfToken ctk = contextView.get(ContextUtils.CSRF_TOKEN_CONTEXT);
// Return the CSRF token wrapped in a Mono, or an empty Mono if no CSRF token is found.
return Mono.justOrEmpty(ctk);
});
}

/**
* Binds an OAuth2 client to the authenticated user.
*
* @param clientRegistrationId The registration ID of the OAuth2 client.
* @param authentication The authentication object containing the user's credentials.
* @param exchange The current server web exchange.
* @return A Mono<Object> object containing the access token of the OAuth2 client.
*/
@GetMapping("bind")
public Mono<Object> bindOauth2(String clientRegistrationId, Authentication authentication, ServerWebExchange exchange) {
// Load the authorized OAuth2 client using the client registration ID, authentication object, and server web exchange.
// Then, retrieve the access token of the OAuth2 client.
return this.clientRepository.loadAuthorizedClient(clientRegistrationId, authentication, exchange)
.flatMap(oAuth2AuthorizedClient -> Mono.just(oAuth2AuthorizedClient.getAccessToken()));
}

/**
* Changes the password of the authenticated user.
*
* @param request The request object containing the current and new password.
* @param authentication The authentication object containing the user's credentials.
* @return A Mono<UserDetails> object of the updated user.
* @throws RestServerException if the new password is the same as the current password.
* @throws RestServerException if the presented password does not match the current password.
*/
@PostMapping("/change/password")
public Mono<UserDetails> changePassword(@Valid @RequestBody ChangePasswordRequest request,
Authentication authentication) {
// Check if the new password is the same as the current password.
if (!request.getPassword().equals(request.getNewPassword())) {
// Throw an exception if the new password is the same as the current password.
throw RestServerException.withMsg("Password and newPassword not match", request);
}
// Retrieve the presented password from the authentication object.
String presentedPassword = (String) authentication.getCredentials();
// Check if the presented password matches the current password.
if (!this.passwordEncoder.matches(presentedPassword, request.getPassword())) {
// Throw an exception if the presented password does not match the current password.
throw RestServerException.withMsg(
"Password verification failed, presented password not match", presentedPassword);
}
// Encode the new password.
String newPassword = this.passwordEncoder.encode(request.getNewPassword());
// Retrieve the UserDetails from the authentication object.
UserDetails userDetails = (UserDetails) authentication.getDetails();
// Update the user's password and return the updated UserDetails.
return this.securityManager.updatePassword(userDetails, newPassword);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,20 +75,22 @@ public SecurityDetails password(String password) {
}

public String getTenantCode() {
var defaultTenantCode = "0";
if (ObjectUtils.isEmpty(this.getTenants())) {
return null;
return defaultTenantCode;
}
return this.getTenants().stream().filter(TenantMemberResponse::getEnabled).findAny()
.map(TenantMemberResponse::getTenantCode).orElse(null);
.map(TenantMemberResponse::getTenantCode).orElse(defaultTenantCode);
}

@JsonGetter
public String getTenantName() {
var defaultTenantName = "默认租户";
if (ObjectUtils.isEmpty(this.getTenants())) {
return null;
return defaultTenantName;
}
return this.getTenants().stream().filter(TenantMemberResponse::getEnabled).findAny()
.map(TenantMemberResponse::getName).orElse(null);
.map(TenantMemberResponse::getName).orElse(defaultTenantName);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ public class Oauth2SuccessHandler extends RedirectServerAuthenticationSuccessHan
@Override
public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
if (!(authentication instanceof OAuth2AuthenticationToken)) {
// 如果不是预期的认证类型,可以选择记录日志或返回错误响应
throw RestServerException.withMsg("Authentication token must be an instance of OAuth2AuthenticationToken",
List.of());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
@RequiredArgsConstructor
public class Oauth2UserService extends DefaultReactiveOAuth2UserService {

private static final SecureRandom SECURE_RANDOM = new SecureRandom();

private final SecurityManager securityManager;

@Override
Expand Down Expand Up @@ -104,8 +106,7 @@ public OAuth2User convertToOauth2User(User details, OAuth2User oAuth2User) {

public static String generateRandoPassword() {
byte[] randomBytes = new byte[16];
SecureRandom secureRandom = new SecureRandom();
secureRandom.nextBytes(randomBytes);
SECURE_RANDOM.nextBytes(randomBytes);
return Base64.getEncoder().encodeToString(randomBytes);
}
}
4 changes: 2 additions & 2 deletions boot/platform/src/main/resources/schema-postgres.sql
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,8 @@ create table if not exists se_menus
pcode varchar(64) not null default '0',
tenant_code varchar(64) not null default '0',
type varchar(20) not null default 'MENU',
authority varchar(512) not null unique,
name varchar(512) not null,
authority varchar(256) not null unique,
name varchar(256) not null,
path text,
sort int default 0,
extend jsonb,
Expand Down
6 changes: 3 additions & 3 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
plugins {
id "org.springframework.boot" version "3.2.5" apply false
id 'io.spring.dependency-management' version '1.1.4' apply false
id 'org.graalvm.buildtools.native' version '0.10.1' apply false
id "org.springframework.boot" version "3.3.0" apply false
id 'io.spring.dependency-management' version '1.1.5' apply false
id 'org.graalvm.buildtools.native' version '0.10.2' apply false
}

ext {
Expand Down

0 comments on commit 234f9f4

Please sign in to comment.