imRajAryan09
JCHJava Community | Help. Code. Learn.
•Created by imRajAryan09 on 9/29/2024 in #java-help
Explain the flow of google auth in spring boot
@Bean
public SecurityFilterChain googleOAuth2SecurityFilterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.securityMatcher(new AntPathRequestMatcher("/oauth2/**"))
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/auth/login/**", "/oauth2/**", "/login/oauth2/**", "/login").permitAll()
.anyRequest().authenticated()
)
.oauth2Login(oauth2 -> oauth2
.loginPage("/auth/login/google")
.defaultSuccessUrl("/dashboard", true)
.failureUrl("/login?error=true")
.userInfoEndpoint(userInfo -> userInfo.userService(googleOAuth2Service))
.successHandler((request, response, authentication) -> {
DefaultOAuth2User oauth2User = (DefaultOAuth2User) authentication.getPrincipal();
String token = oauth2User.getAttribute("token");
response.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token);
})
)
.exceptionHandling(ex -> ex
.authenticationEntryPoint(new CustomOAuth2AuthenticationEntryPoint())
.accessDeniedHandler(new CustomAccessDeniedHandler())
)
.logout(logout -> logout
.logoutUrl("/logout")
.logoutSuccessUrl("/login?logout=true")
.addLogoutHandler(logoutHandlerService)
)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.build();
}
@Bean
public SecurityFilterChain googleOAuth2SecurityFilterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.securityMatcher(new AntPathRequestMatcher("/oauth2/**"))
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/auth/login/**", "/oauth2/**", "/login/oauth2/**", "/login").permitAll()
.anyRequest().authenticated()
)
.oauth2Login(oauth2 -> oauth2
.loginPage("/auth/login/google")
.defaultSuccessUrl("/dashboard", true)
.failureUrl("/login?error=true")
.userInfoEndpoint(userInfo -> userInfo.userService(googleOAuth2Service))
.successHandler((request, response, authentication) -> {
DefaultOAuth2User oauth2User = (DefaultOAuth2User) authentication.getPrincipal();
String token = oauth2User.getAttribute("token");
response.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token);
})
)
.exceptionHandling(ex -> ex
.authenticationEntryPoint(new CustomOAuth2AuthenticationEntryPoint())
.accessDeniedHandler(new CustomAccessDeniedHandler())
)
.logout(logout -> logout
.logoutUrl("/logout")
.logoutSuccessUrl("/login?logout=true")
.addLogoutHandler(logoutHandlerService)
)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.build();
}
4 replies