Skip to content

Commit

Permalink
Eagerly fetch csrf token for single page application
Browse files Browse the repository at this point in the history
  • Loading branch information
Alf-Melmac committed Feb 21, 2023
1 parent f85fba3 commit 9134561
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package de.webalf.slotbot.configuration.authentication.website;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
* @author Alf
* @since 21.02.2023
*/
@Component
public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
// https://github.com/spring-projects/spring-security/issues/12094#issuecomment-1294150717
CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
csrfToken.getToken();

super.onAuthenticationSuccess(request, response, authentication);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class OAuth2EndpointConfig {
private final DiscordAuthenticationService discordAuthenticationService;
private final AuthenticationSuccessHandler authenticationSuccessHandler;

@Bean
protected SecurityFilterChain oAuthUserFilterChain(HttpSecurity http) throws Exception {
Expand Down Expand Up @@ -65,6 +66,7 @@ protected SecurityFilterChain oAuthUserFilterChain(HttpSecurity http) throws Exc
.oauth2Login()
.loginPage("/oauth2/authorization/discord")
.defaultSuccessUrl("/events")
.successHandler(authenticationSuccessHandler)
.tokenEndpoint().accessTokenResponseClient(accessTokenResponseClient())
.and()
.userInfoEndpoint().userService(oAuthUserService());
Expand Down

0 comments on commit 9134561

Please sign in to comment.