I'm working on a Spring Boot application that integrates Google Authentication. I've set up the authentication flow to redirect users to http://localhost:8080/david-core/oauth2/authorization/google for the Google sign-in page. However, after selecting my Google account, I'm being redirected back to the URL http://localhost:8080/david-core/oauth2/code/google, and I'm encountering a 302 status code. The error message I see is "too many requests."
I've checked the backend logs, but I'm not seeing any clear error messages there. Similarly, in the network tab, I'm only seeing the 302 status code without additional information. Here are the details of the request and response headers:
Request URL:
https://accounts.google.com/signin/oauth/consent?authuser=0&part=AJi8hAOEdMF1IEbyffElZiFCvtY0Kt7OvFyp0NsplSGhhNwKhj5q2BTwVoY6smr6UvyNJJM2guCHubu5hwhGWZnc1I6pHiSgeoGmhCZTa8BTRR40nW6-P5HDfIuyf_Wc0UhVV6jrvCqUxfngJfjEFHAR3DTMrlZfjEVzpMIstziuawocqs6kxAo3haS7ct5BeJYoDptPYqyWk12fFmSIxNJWmhCESUt2Ah2K6sSjvEv8NADUCsGEeBnr3NVDmJnpKAOuPhetCX_XaQ3Z44PnKrGeHe3_zC9ySrbtN9qpVLZqump-lkNsMoeJKCLEYy6eVlbDV8q4UezUj_SsG1-zUSdKjVV6RrDRQLmVv42gQj18hgGQX5ZBs279ubVHWBW2dgGzCsv6ok6_UHjrsQYtaeYtmRrEGkkVkEZ1u-mR-ZONTZyKfgkRgGlQ5jJ7hfcRo4ETXMKSLVeOIQa6nbwY6EyAdBurFfWIyQ&as=S1543709863%3A1692062127598219&client_id=33573278563-e6pfelv8h4e18lfmtgmnj5g5lmi0a655.apps.googleusercontent.com&pli=1&rapt=AEjHL4PGI_ts8e_DiJEmwW2WXe3pxJrhuefN6jAf7-5m7PLEgsNyyLpHDE7U-Z2DnV4cmJRcOBNanMXMY4f-w1u85mYclV7urQ
Request Method: GET
Status Code: 302
I have thoroughly checked my backend, but I'm not finding any concrete errors. Is there anything specific I should be looking for or any suggestions on how to troubleshoot this issue further? Any help would be greatly appreciated.
code:
Security Class`
`http
.oauth2Login(oauth2Login ->
oauth2Login
.loginProcessingUrl("/login")
.loginPage("/oauth2/code/google")
.userInfoEndpoint()
.userService(oauthUserService)
.and()
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,Authentication authentication) throws IOException, ServletException {
CustomOAuth2User oauthUser = (CustomOAuth2User) authentication.getPrincipal();
userService.processOAuthPostLogin(oauthUser.getEmail());
response.sendRedirect("http://localhost:3000");
}
})
);`
`CustomOAuth2User class`
`public class CustomOAuth2User implements OAuth2User {
private OAuth2User oAuth2User;
public CustomOAuth2User(OAuth2User oAuth2User) {
this.oAuth2User = oAuth2User;
}
@Override
public Map<String, Object> getAttributes() {
return oAuth2User.getAttributes();
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return oAuth2User.getAuthorities();
}
@Override
public String getName() {
return oAuth2User.getAttribute("name");
}
public String getEmail() {
return oAuth2User.<String>getAttribute("email");
}
}`
`CustomOAuth2UserService class`
`@Service
public class CustomOAuth2UserService extends DefaultOAuth2UserService {
@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException{
OAuth2User user = super.loadUser(userRequest);
return new CustomOAuth2User(user);
}
}`
`User Service`
`@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void processOAuthPostLogin(String username) {
UserEntity existUser = userRepository.findByUsername(username);
if (existUser == null) {
UserEntity newUser = new UserEntity();
newUser.setUsername(username);
newUser.setProvider(Provider.GOOGLE);
//newUser.setEnabled(true);
userRepository.save(newUser);
}
}
}`
I used this doucmentation to complete the code : https://www.codejava.net/frameworks/spring-boot/oauth2-login-with-google-example
Debugging: I added debug statements to my Spring Boot application's relevant code sections, such as the Google Authentication configuration and controller methods. However, I couldn't capture any errors or unexpected behavior during the authentication flow.
I encountered a situation where I'm using custom JWT authentication in my Spring Boot application. In this setup, I configured URLs not to go through the JWT process, and this part works as expected. When the URLs match certain conditions, the code inside the following block executes as anticipated:``
`if (request.getServletPath().equals("/user/add") || request.getServletPath().equals("/user/update") || /* ...other paths... */) {
filterChain.doFilter(request, response);
}`
However, the issue arises when I go deeper into my codebase. Although I have other APIs that work without JWT authentication, in this particular case, after the code reaches the following line:
`filterChain.doFilter(request, response);`
It doesn't execute the expected functions in my other classes. The program flow seems to be similar to other functional APIs, but the behavior is inconsistent.
To provide context, this is part of my doFilterInternal method where I'm handling JWT authentication:
`@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
// ... (previous code)
try {
filterChain.doFilter(request, response);
} catch (Exception e) {
log.info("Error during login: {}", e.getMessage());
}
}`
I've performed debugging to trace the execution flow, but I couldn't identify the exact point of the issue. It's worth noting that I've successfully used this approach for other endpoints without any problems. My expectation is that the functions related to the URLs specified should run as intended within the filterChain.doFilter(request, response); block, just like other endpoints.
Has anyone encountered a similar situation or can provide guidance on how to troubleshoot this behavior further? Any insights or suggestions would be greatly appreciated.`
here is full code
`public class CustomAuthorizationFilter extends OncePerRequestFilter {
private final JwtConfig jwtConfig;
private final SecretKey secretKey;
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
if (request.getServletPath().equals("/user/add") || request.getServletPath().equals("/user/update") || /* ...other paths... */) {
filterChain.doFilter(request, response);
} else {
String authorizationHeader = request.getHeader(jwtConfig.getAuthorizationHeader());
if (Strings.isNullOrEmpty(authorizationHeader) || !authorizationHeader.startsWith(jwtConfig.getTokenPrefix())) {
filterChain.doFilter(request, response);
}
String token = authorizationHeader.replace(jwtConfig.getTokenPrefix(), "");
try {
Jws<Claims> claimsJws = Jwts.parserBuilder()
.setSigningKey(secretKey)
.build()
.parseClaimsJws(token);
Claims body = claimsJws.getBody();
String username = body.getSubject();
var authorities = (List<Map<String, String>>) body.get("authorities");
Set<SimpleGrantedAuthority> simpleGrantedAuthorities = authorities.stream()
.map(m -> new SimpleGrantedAuthority(m.get("authority")))
.collect(Collectors.toSet());
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
username,
null,
simpleGrantedAuthorities
);
SecurityContextHolder.getContext().setAuthentication(authentication);
} catch (JwtException ex) {
log.info("Error in login: {}", ex.getMessage());
HashMap<String, String> error = new HashMap<>();
error.put("error_message", ex.getMessage());
response.setContentType(APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
new ObjectMapper().writeValue(response.getOutputStream(), error);
}
try {
filterChain.doFilter(request, response);
} catch (Exception e) {
log.info("Error in login: {}", e.getMessage());
}
}
}
}
`