Home > Software design >  How do I redirect to a specific uri after Google oauth using Spring Boot
How do I redirect to a specific uri after Google oauth using Spring Boot

Time:01-22

I'm implementing a server using Spring Boot. After the user do an oauth login, I want the user to go redirect to a specific uri so I can let the user register or login. The Google OAuth login seems like it is working fine but it keeps going to "/" uri. I want to user to be redirected to "/api/v1/member/oauth"

This is my Spring Security setup.

...
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .cors()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/swagger-ui/**", "/swagger-resources/**", "/v2/api-docs")
                .permitAll()
                .anyRequest()
                .permitAll()
                .and()
                .oauth2Login()
                .userInfoEndpoint()
                .userService(customOAuth2MemberService);
    }
...

This is the OAuth service that a user is directed to. (This works fine)

@Service
@RequiredArgsConstructor
public class CustomOAuth2MemberService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {

    @Override
    public OAuth2User loadUser(OAuth2UserRequest userRequest) {
        OAuth2UserService<OAuth2UserRequest, OAuth2User> delegate = new DefaultOAuth2UserService();

        OAuth2User oAuth2User;

        try {
            oAuth2User = delegate.loadUser(userRequest);
        } catch (OAuth2AuthenticationException e) {
            throw new CustomException(OAUTH_FAIL);
        }

        return new DefaultOAuth2User(oAuth2User.getAuthorities(), oAuth2User.getAttributes(), "sub");
    }
}

I want to get the DefaultOAuth2User which is returned from the above to this uri.

@PostMapping("/api/v1/member/oauth")
    public Object registerOrLogin(DefaultOAuth2User defaultOAuth2user) {


        return ResponseEntity.status(200)
                .body(DefaultResponseDto.builder()
                        .responseCode("MEMBER_LOGIN")
                        .build());
    }

It currently is not going to this uri and is redirected to "/".

CodePudding user response:

Try to use

.oauth2Login()
.defaultSuccessUrl("/api/v1/member/oauth")

this should override post-authentication behavior and redirect to the desired page after successful login. Also, there is a similar method for setting redirection URL for failed authentication .failureUrl("url").

CodePudding user response:

Spring-Security AbstractAuthenticationProcessingFilter class has successfulAuthentication() methos, which defines what happens when a User is successfully authenticated. You can register your success handler and put your redirect logic there.

But here is a catch, when using OAuth2.0, we need to specify redirect-uri to which user will be landed after client receives an access-token.

If you are okay with this Oauth's redirect-uri, do not alter the redirect in success handler or if you need to redirect irrespective of that, use response.sendRedirect("/social-login-sample/some-page");

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .cors()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/swagger-ui/**", "/swagger-resources/**", "/v2/api-docs")
                .permitAll()
                .anyRequest()
                .permitAll()
                .and()
                .oauth2Login()
                .userInfoEndpoint()
                .userService(customOAuth2MemberService)
                .and()
                .successHandler(
                    new AuthenticationSuccessHandler() {

                      @Override
                      public void onAuthenticationSuccess(
                          HttpServletRequest request,
                          HttpServletResponse response,
                          Authentication authentication)
                          throws IOException, ServletException {

                        // authentication.getName() : Principal Name
                        CustomOAuth2User oauthUser = (CustomOAuth2User) authentication.getPrincipal();

                        // Check if user is registered in your Database, if not, register new user
                        //userService.processAuthenticatedUser(oauthUser.getEmail());

                        // Get actual redirect-uri set in OAuth-Provider(Google, Facebook)
                        String redirectUri =
                            UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request))
                                .replaceQuery(null)
                                .build()
                                .toUriString();

                        log.info("redirectUri: {}", redirectUri);

                        // Ignore redirect-uri, and send user to a different page instead...
                        // response.sendRedirect("/social-login-sample/some-ther-page");
                      }
                    })
    }
  • Related