Fix the problem of logging in successfully even if request not permitted (#4101)

#### What type of PR is this?

/kind bug
/area core

#### What this PR does / why we need it:

This is a bug introduced from https://github.com/halo-dev/halo/pull/4062. I have overridden onAuthenticationSuccess to create rate limiter in advance instead of invoking `securityContextRepository#save` before.

See https://github.com/halo-dev/halo/pull/4099#issuecomment-1598074131 for more.

#### Special notes for your reviewer:

1. Try to log in with incorrect password three times
2. Log in with correct password and check if the response headers contain `Set-Cookie`

#### Does this PR introduce a user-facing change?

```release-note
None
```
pull/4099/head^2
John Niang 2023-06-21 11:26:12 +08:00 committed by GitHub
parent 2fd9cbde33
commit a19f342b47
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 20 additions and 5 deletions

View File

@ -91,7 +91,8 @@ public class UsernamePasswordAuthenticator implements AdditionalWebFilter {
this.rateLimiterRegistry = rateLimiterRegistry;
this.messageSource = messageSource;
this.authenticationWebFilter = new AuthenticationWebFilter(authenticationManager());
this.authenticationWebFilter =
new UsernamePasswordAuthenticationWebFilter(authenticationManager());
configureAuthenticationWebFilter(this.authenticationWebFilter);
}
@ -179,6 +180,23 @@ public class UsernamePasswordAuthenticator implements AdditionalWebFilter {
return locale == null ? Locale.getDefault() : locale;
}
private class UsernamePasswordAuthenticationWebFilter extends AuthenticationWebFilter {
public UsernamePasswordAuthenticationWebFilter(
ReactiveAuthenticationManager authenticationManager) {
super(authenticationManager);
}
@Override
protected Mono<Void> onAuthenticationSuccess(Authentication authentication,
WebFilterExchange webFilterExchange) {
return super.onAuthenticationSuccess(authentication, webFilterExchange)
.transformDeferred(createIPBasedRateLimiter(webFilterExchange.getExchange()))
.onErrorResume(RequestNotPermitted.class,
e -> handleRequestNotPermitted(e, webFilterExchange.getExchange()));
}
}
public class LoginSuccessHandler implements ServerAuthenticationSuccessHandler {
private final ServerAuthenticationSuccessHandler defaultHandler =
@ -206,10 +224,7 @@ public class UsernamePasswordAuthenticator implements AdditionalWebFilter {
.bodyValue(principal)
.flatMap(serverResponse ->
serverResponse.writeTo(exchange, context));
})
.transformDeferred(createIPBasedRateLimiter(exchange))
.onErrorResume(RequestNotPermitted.class,
e -> handleRequestNotPermitted(e, exchange));
});
}
}