<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Oussemasahbeni on Medium]]></title>
        <description><![CDATA[Stories by Oussemasahbeni on Medium]]></description>
        <link>https://medium.com/@oussemasahbeni300?source=rss-b94d6b770ff7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*a090poSM9lcxXtcZkDeQpA.jpeg</url>
            <title>Stories by Oussemasahbeni on Medium</title>
            <link>https://medium.com/@oussemasahbeni300?source=rss-b94d6b770ff7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 17:08:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oussemasahbeni300/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Integrating Google Social Login with Angular 17 and Spring Boot 3]]></title>
            <link>https://medium.com/@oussemasahbeni300/integrating-google-social-login-with-angular-17-and-spring-boot-3-344ae8178a8d?source=rss-b94d6b770ff7------2</link>
            <guid isPermaLink="false">https://medium.com/p/344ae8178a8d</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[google-sign-in]]></category>
            <category><![CDATA[oauth2]]></category>
            <dc:creator><![CDATA[Oussemasahbeni]]></dc:creator>
            <pubDate>Fri, 09 Aug 2024 14:15:51 GMT</pubDate>
            <atom:updated>2024-08-13T15:45:13.273Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*lhGn14DgjKvDzGqokjslZw.png" /></figure><p>Google social login allows users to authenticate using their Google account, simplifying the sign-in process and enhancing user experience. In this article, we will explore how to integrate Google social login into an application using Angular for the frontend and Spring Boot for the backend. But first, let’s clarify some key concepts and the tools we will be using.<br>Key Concepts and Tools</p><p><strong>OAuth 2.0:</strong></p><p>OAuth 2.0 is an open standard for access delegation, commonly used to grant websites or applications limited access to a user’s data without exposing the user’s credentials. It operates through a series of token exchanges, providing a secure method for authenticating users.</p><p><strong>Resource Server:</strong></p><p>In OAuth 2.0, the resource server is the server hosting the user’s protected resources. It accepts and validates access tokens issued by the authorization server (in this case, Google), allowing clients to access the protected resources.</p><p><strong>Authorization Server:</strong></p><p>The authorization server is responsible for authenticating the user and issuing access tokens. For Google social login, Google acts as the authorization server, providing the necessary tokens after user authentication.</p><p><strong>Client:</strong></p><p>The client in this context refers to the application that the user is trying to access, which will request an authorization grant from the user to obtain the necessary tokens.</p><p><strong>Angular and Spring Boot Versions:</strong></p><p>Angular: We’ll use Angular 17.1.0, a popular frontend framework that provides a robust structure for building dynamic web applications.<br> Spring Boot: We’ll use Spring Boot 3.3.2, a framework that simplifies the setup of new Spring applications and provides built-in support for OAuth 2.0, making it easy to secure your application with social login.</p><h3><strong>Step 1: Setting Up Google Developer Console</strong></h3><p>Create a Google Cloud Project:<br> Visit the <a href="https://console.cloud.google.com/welcome?project=social-login-demo-432009">Google Cloud Console</a>.<br> Create a new project, which will be the central place where you manage your OAuth 2.0 credentials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*sbI6eXnNoiaQQ3RR9reGbg.png" /><figcaption>Click on NEW PROJECT</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*GZneZ_4Zl606ffzhSqzKzg.png" /><figcaption>Provide the project name</figcaption></figure><p>Enable OAuth 2.0:<br> Navigate to Credentials.<br> Click on Create Credentials and select OAuth 2.0 Client IDs.<br> Configure the consent screen by providing your application’s information. This screen is shown to users when requesting permission to access their data.</p><p>Start by configuring the oauth2 consent screen</p><p>Check the external button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*WXG-mG7C6HkUI0GrQXzr0g.png" /></figure><p>and then just provide the App name, app logo if you want, and Developer contact information</p><p>Choose Web application as the application type.<br> Add your Authorized redirect URIs for both backend and frontend, such as <a href="http://localhost:9000/api/v1/login/oauth2/code/google">http://localhost:9000/api/v1/login/oauth2/code/google</a> for Spring Boot and <a href="http://localhost:4200/">http://localhost:4200/callback</a> and <a href="http://localhost/">http://localhost</a> for Authorized JavaScript origins ( Angular app).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*anKp0hyh7_fstzGJ2l9qzg.png" /></figure><p>Save your credentials to obtain the Client ID and Client Secret ( we will need them later in our backend configuration and also in the frontend).</p><h3><strong>Step 2: Configuring Spring Boot Backend</strong></h3><p>Add Dependencies:<br> In your pom.xml, add the necessary dependencies for OAuth 2.0 , Spring Security, Postgres, and Lombok to handle social login and secure your application.</p><p>pom.xml</p><pre>&lt;dependencies&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>        &lt;!-- Oauth2 Client--&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-oauth2-client&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>        <br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>        &lt;!-- Postgres--&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.postgresql&lt;/groupId&gt;<br>            &lt;artifactId&gt;postgresql&lt;/artifactId&gt;<br>            &lt;scope&gt;runtime&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;!-- Swagger--&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springdoc&lt;/groupId&gt;<br>            &lt;artifactId&gt;springdoc-openapi-starter-webmvc-ui&lt;/artifactId&gt;<br>            &lt;version&gt;2.3.0&lt;/version&gt;<br>        &lt;/dependency&gt;<br>        &lt;!-- Lombok  --&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>            &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>            &lt;optional&gt;true&lt;/optional&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>            &lt;scope&gt;test&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-security-test&lt;/artifactId&gt;<br>            &lt;scope&gt;test&lt;/scope&gt;<br>        &lt;/dependency&gt;<br><br>        &lt;!-- Jwt dependencies--&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>            &lt;artifactId&gt;jjwt-api&lt;/artifactId&gt;<br>            &lt;version&gt;0.11.5&lt;/version&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>            &lt;artifactId&gt;jjwt-impl&lt;/artifactId&gt;<br>            &lt;version&gt;0.11.5&lt;/version&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>            &lt;artifactId&gt;jjwt-jackson&lt;/artifactId&gt;<br>            &lt;version&gt;0.11.5&lt;/version&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br><br>    &lt;build&gt;<br>        &lt;plugins&gt;<br>            &lt;plugin&gt;<br>                &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>                &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;<br>                &lt;configuration&gt;<br>                    &lt;excludes&gt;<br>                        &lt;exclude&gt;<br>                            &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>                            &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>                        &lt;/exclude&gt;<br>                    &lt;/excludes&gt;<br>                &lt;/configuration&gt;<br>            &lt;/plugin&gt;<br>        &lt;/plugins&gt;<br>    &lt;/build&gt;</pre><p>Application Properties Configuration:</p><p>In application.yml, configure the Google OAuth 2.0 client credentials. This includes the client ID, client secret, and other relevant settings like the scope and redirect URI.</p><p>application.yml</p><pre>spring:<br>  application:<br>    name: social-login-demo<br>  datasource:<br>    url: jdbc:postgresql://localhost:5432/social-login-demo<br>    username: YourPostgresUsername<br>    password: YourPostgresPassword<br>    driver-class-name: org.postgresql.Driver<br>  jpa:<br>    hibernate:<br>      ddl-auto: update<br>    properties:<br>      hibernate:<br>        format_sql: true<br>        dialect: org.hibernate.dialect.PostgreSQLDialect<br>    database: postgresql<br>    database-platform: org.hibernate.dialect.PostgreSQLDialect<br>  security:<br>    oauth2:<br>      client:<br>        registration:<br>          google:<br>            client-id: YourClientId<br>            client-secret: YourClientSecret<br><br><br>application:<br>  security:<br>    jwt:<br>      secret-key: YourSecretKey<br>      expiration: 86400000 # a day<br>  cors:<br>    allowed-origins: http://localhost:4200<br>  auth-code:<br>    expiration: 172800 # 2 days<br><br><br>springdoc:<br>  api-docs:<br>    path: /api-docs<br>  swagger-ui:<br>    operationsSorter: method<br>    path: /swagger-ui.html<br><br>logging:<br>  level:<br>    org:<br>      springframework:<br>        security: DEBUG<br><br>server:<br>  port: 9000<br>  servlet:<br>    context-path: /api/v1</pre><p>Security Configuration:</p><p>Create a SecurityConfig class to manage your application’s security configuration. This will include setting up OAuth 2.0 login, specifying success and failure handlers, and defining which paths require authentication.</p><p>SecurityConfig.java</p><pre>@Configuration<br>@EnableWebSecurity<br>@RequiredArgsConstructor<br>@EnableMethodSecurity<br>public class SecurityConfig {<br><br>    private final JwtFilter jwtAuthFilter;<br>    private final Oauth2LoginSuccessHandler oauth2LoginSuccessHandler;<br>    private final Oauth2LoginFailureHandler oauth2LoginFailureHandler;<br><br>    private static final String[] AUTH_WHITE_LIST = {&quot;/api/v1/auth/**&quot;,<br>            &quot;/v2/api-docs&quot;,<br>            &quot;/v3/api-docs&quot;,<br>            &quot;/v3/api-docs/**&quot;,<br>            &quot;/swagger-resources&quot;,<br>            &quot;/swagger-resources/**&quot;,<br>            &quot;/configuration/ui&quot;,<br>            &quot;/configuration/security&quot;,<br>            &quot;/swagger-ui/**&quot;,<br>            &quot;/webjars/**&quot;,<br>            &quot;/swagger-ui.html&quot;};<br><br>    @Bean<br>    public SecurityFilterChain jwtAuthorizationSecurityFilterChain(HttpSecurity http) throws Exception {<br>        http<br>                .cors(Customizer.withDefaults())<br>                .csrf(AbstractHttpConfigurer::disable)<br>                .sessionManagement(session -&gt; session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) // JWT doesn&#39;t need sessions<br>                .authorizeHttpRequests(authorizeRequests -&gt;<br>                        authorizeRequests<br>                                .requestMatchers(AUTH_WHITE_LIST).permitAll()<br>                                .anyRequest().authenticated()<br>                )<br>                // Add the JWT filter before the UsernamePasswordAuthenticationFilter<br>                .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)<br>                // Enable OAuth2 login<br>                .oauth2Login(customizer -&gt; customizer<br>                        .successHandler(oauth2LoginSuccessHandler)<br>                        .failureHandler(oauth2LoginFailureHandler)<br>                );<br>        return http.build();<br>    }</pre><p>The <strong>SecurityConfig</strong> class sets up OAuth2 login with Spring Security, integrating custom handlers for specific roles:</p><ul><li><strong>Oauth2LoginSuccessHandler</strong>: This handles what happens after a successful OAuth2 login, such as persisting user information or generating tokens. We’ll use it later to manage user data and control post-login redirects.</li><li><strong>Oauth2LoginFailureHandler</strong>: This manages the process when OAuth2 login fails, handling errors like invalid credentials. It ensures that failures are handled gracefully, providing appropriate feedback to users.</li></ul><p>These handlers are crucial for customizing the login flow, ensuring that successful logins are processed correctly and any issues are properly managed.</p><p>User Entity, Repository and controller:</p><p>Define a User entity that maps to your database schema, and create a repository for managing CRUD operations related to user data. Along side a controller to get the user information</p><p>User.java</p><pre>package com.demo.social.user;<br>// import the needed classes<br>@Getter<br>@Setter<br>@AllArgsConstructor<br>@NoArgsConstructor<br>@SuperBuilder<br>@Entity<br>@Table(name = &quot;users&quot;)<br>@EntityListeners(AuditingEntityListener.class)<br>public class User implements UserDetails, Principal {<br><br><br>    @Id<br>    @GeneratedValue()<br>    private UUID id;<br><br>    @Column(name = &quot;firstName&quot;, nullable = false)<br>    private String firstName;<br><br>    @Column(name = &quot;providerId&quot;, unique = true)<br>    private String providerId;<br><br>    @Column(name = &quot;provider&quot;)<br>    private String provider;<br><br>    @Column(name = &quot;lastName&quot;, nullable = false)<br>    private String lastName;<br><br>    @Column(name = &quot;email&quot;, nullable = false, unique = true)<br>    private String email;<br><br>    @Column(name = &quot;phoneNumber&quot;)<br>    private String phoneNumber;<br><br>    private String profilePictureUrl;<br><br>    @Column(name = &quot;emailVerified&quot;, nullable = false)<br>    private boolean emailVerified;<br><br>    @Column(name = &quot;enabled&quot;, nullable = false)<br>    private boolean enabled;<br><br>    @Column(name = &quot;accountLocked&quot;, nullable = false)<br>    private boolean accountLocked;<br><br>    @Column(name = &quot;dateOfBirth&quot;)<br>    private LocalDate dateOfBirth;<br><br>    @Column(name = &quot;address&quot;)<br>    private String address;<br><br>    @Enumerated(EnumType.STRING)<br>    private Role role;<br><br>    @CreatedBy<br>    private String createdBy;<br>    @LastModifiedBy<br>    private String lastModifiedBy;<br>    @CreatedDate<br>    private LocalDateTime createdAt;<br>    @LastModifiedDate<br>    private LocalDateTime updatedAt;<br>    @Version<br>    private Integer version;<br><br>    public String getFullName() {<br>        return firstName + &quot; &quot; + lastName;<br>    }<br><br>    /**<br>     * Represents the name of the user which is the id of the user.<br>     * This method is used in Spring Security for authentication purposes.<br>     * ----<br>     * In Spring Security, the `Principal` interface represents the currently authenticated user.<br>     * The `getName` method is used to retrieve the unique identifier of the user, which in this case is the user&#39;s id.<br>     * This id is inherited from the `BaseEntity` class and is used to uniquely identify the user in the system.<br>     * ----<br>     *<br>     * @return the id of the user as a String<br>     */<br>    @Override<br>    public String getName() {<br>        return id.toString();<br>    }<br><br><br>    /**<br>     * Represents the authorities of the user.<br>     * By default, the roles of the user are considered as authorities.<br>     * Authorities are the permissions or roles granted to the user.<br>     * This method is used in Spring Security for authorization purposes.<br>     * -------<br>     * In Spring Security, the `UserDetails` interface requires the implementation of the `getAuthorities` method.<br>     * This method returns a collection of `GrantedAuthority` objects, which represent the roles or permissions assigned to the user.<br>     * Here, we map each `RoleEntity` to a `SimpleGrantedAuthority` using the role&#39;s name.<br>     * This allows Spring Security to understand what roles or permissions the user has.<br>     *<br>     * @return a collection of authorities granted to the user<br>     */<br><br>    @Override<br>    public Collection&lt;? extends GrantedAuthority&gt; getAuthorities() {<br>        return Collections.singleton(new SimpleGrantedAuthority(role.name()));<br>    }<br><br>    // we dont need a password because the user will authenticate <br>    // with google instead<br>    @Override<br>    public String getPassword() {<br>        return null;<br>    }<br><br>    /**<br>     * Returns the username of the user, which is the user&#39;s email.<br>     * This method is used in Spring Security for authentication purposes.<br>     * ----<br>     * In Spring Security, the `UserDetails` interface requires the implementation of the `getUsername` method.<br>     * This method returns the username used for authentication, which in this case is the user&#39;s email.<br>     * The email is used as the unique identifier for the user during the login process.<br>     * ----<br>     *<br>     * @return the email of the user<br>     */<br>    @Override<br>    public String getUsername() {<br>        return getId().toString();<br>    }<br><br>    @Override<br>    public boolean isAccountNonExpired() {<br>        return true;<br>    }<br><br>    @Override<br>    public boolean isCredentialsNonExpired() {<br>        return true;<br>    }<br><br>    @Override<br>    public boolean isEnabled() {<br>        return enabled;<br>    }<br>}</pre><p>UserRepository.java</p><pre>@Repository<br>public interface UserRepository extends JpaRepository&lt;User, UUID&gt; {<br>    Optional&lt;User&gt; findByEmail(String email);<br>}</pre><p>The <strong>User</strong> class is a JPA entity that integrates with Spring Security by implementing UserDetails, storing user information like email and role. It also supports auditing with automatic tracking of creation and modification dates.</p><p>The <strong>UserRepository</strong> extends JpaRepository to handle database operations for User entities and includes a method to find users by email, essential for OAuth2 login.</p><pre>@RestController<br>@RequestMapping(&quot;/user&quot;)<br>@RequiredArgsConstructor<br>public class UserController {<br><br>    private final UserService userService;<br>    private final UserMapper userMapper;<br><br>    @GetMapping(&quot;/me&quot;)<br>    public ResponseEntity&lt;UserDto&gt; getUser() {<br>       Authentication authentication = SecurityContextHolder.getContext().getAuthentication();<br>        var principal =(User) authentication.getPrincipal();<br>        return ResponseEntity.ok(userMapper.toUserDto(principal));<br>    }<br>}</pre><p>UserController will allow us to get the current user information using the api “/me”, the authentication will be filled in the jwt filter class, and we will see its implementation later</p><p><strong>Auditing with JPA:</strong></p><p>Enable JPA Auditing to automatically track and record metadata like creation and modification timestamps in your database entities. This is done by adding <a href="http://twitter.com/EnableJpaAuditing">@EnableJpaAuditing</a> to your main application class or a configuration class.</p><p>SocialLoginBackendApplication.java</p><p>The annotation <a href="http://twitter.com/EnableJpaAuditing">@EnableJpaAuditing</a> is required otherwise the auditing will not work.</p><pre>@SpringBootApplication<br>@EnableJpaAuditing(auditorAwareRef = &quot;auditorAware&quot;)<br>public class SocialLoginBackendApplication {<br>    public static void main(String[] args) {<br>        SpringApplication.run(SocialLoginBackendApplication.class, args);<br>    }<br>}<br><br></pre><p>ApplicationAduitAware.java</p><pre>public class ApplicationAuditAware implements AuditorAware&lt;String&gt; {<br><br>    @Override<br>    @NonNull<br>    public Optional&lt;String&gt; getCurrentAuditor() {<br>        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();<br>        if (authentication == null || !authentication.isAuthenticated() || authentication instanceof AnonymousAuthenticationToken) {<br>            return Optional.empty();<br>        }<br>        String id = authentication.getName();<br>        return Optional.of(id);<br>    }<br>}</pre><p>The <strong>ApplicationAuditAware</strong> class implements AuditorAware&lt;String&gt;, which is used to automatically populate auditing fields like createdBy and lastModifiedBy in JPA entities.</p><pre>@Configuration<br>@RequiredArgsConstructor<br>public class BeansConfig {<br><br>    @Value(&quot;${application.cors.allowed-origins:*}&quot;)<br>    private List&lt;String&gt; allowedOrigins;<br><br>    @Bean<br>    public AuditorAware&lt;String&gt; auditorAware() {<br>        return new ApplicationAuditAware();<br>    }<br><br>    @Bean<br>    public CorsFilter corsFilter() {<br>        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();<br>        final CorsConfiguration config = new CorsConfiguration();<br><br>        // Allow credentials (cookies, authorization headers, etc.) to be included in requests<br>        config.setAllowCredentials(true);<br><br>        // Set the allowed origins for CORS requests<br>        config.setAllowedOrigins(allowedOrigins);<br><br>        // Allow all headers in CORS requests<br>        config.setAllowedHeaders(List.of(&quot;*&quot;));<br><br>        // Allow all HTTP methods in CORS requests<br>        config.setAllowedMethods(List.of(&quot;*&quot;));<br><br>        // Register the CORS configuration for all paths<br>        source.registerCorsConfiguration(&quot;/**&quot;, config);<br>        return new CorsFilter(source);<br>    }<br>}</pre><p>The <strong>BeansConfig</strong> class defines two beans:</p><ol><li><strong>AuditorAware Bean</strong>: Provides ApplicationAuditAware to handle entity auditing by tracking the current user.</li><li><strong>CorsFilter Bean</strong>: Configures CORS to allow all origins, headers, and methods, supporting secure cross-origin requests.</li></ol><p>These beans are essential for automatic auditing and handling cross-origin requests effectively.</p><h3><strong>Step 3: Implement the success Handler and the failure handler</strong></h3><pre>package com.demo.social.security.oauth2;<br><br><br>import com.demo.social.enums.Role;<br>import com.demo.social.security.JwtService;<br>import com.demo.social.user.User;<br>import com.demo.social.user.UserRepository;<br>import jakarta.servlet.ServletException;<br>import jakarta.servlet.http.HttpServletRequest;<br>import jakarta.servlet.http.HttpServletResponse;<br>import lombok.RequiredArgsConstructor;<br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.security.core.Authentication;<br>import org.springframework.security.core.context.SecurityContextHolder;<br>import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;<br>import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;<br>import org.springframework.security.web.authentication.AuthenticationSuccessHandler;<br>import org.springframework.stereotype.Service;<br><br>import java.io.IOException;<br>import java.util.HashMap;<br>import java.util.UUID;<br><br>/**<br> * Service to handle successful OAuth2 login.<br> */<br>@RequiredArgsConstructor<br>@Slf4j<br>@Service<br>public class Oauth2LoginSuccessHandler implements AuthenticationSuccessHandler {<br><br>    private final UserRepository userRepository;<br>    private final JwtService jwtService;<br><br>    /**<br>     * Handles successful authentication by processing the authenticated user,<br>     * updating user information if necessary, and generating JWT tokens.<br>     *<br>     * @param request       the HttpServletRequest<br>     * @param response      the HttpServletResponse<br>     * @param authentication the Authentication object containing user details<br>     * @throws IOException      if an input or output error occurs<br>     * @throws ServletException if a servlet error occurs<br>     */<br>    @Override<br>    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,<br>                                        Authentication authentication) throws IOException, ServletException {<br>        log.info(&quot;Authentication: {}&quot;, authentication);<br><br>        // Get the user details from the authentication object<br>        DefaultOidcUser oidcUser = (DefaultOidcUser) authentication.getPrincipal();<br>        // Convert the user details to AppUser<br>        AppUser appUser = AppUser.fromGoogleUser(oidcUser);<br>        User user = userRepository.findByEmail(appUser.getEmail()).orElse(null);<br><br>        //  If the user is not found, create a new user<br>        if (user == null) {<br>            String providerId = appUser.getId(); // This is the &#39;sub&#39; attribute from Google<br>            OAuth2AuthenticationToken authenticationToken = (OAuth2AuthenticationToken) authentication;<br>            String provider = authenticationToken.getAuthorizedClientRegistrationId();<br><br>            var userToSave = User.builder()<br>                    .id(UUID.randomUUID())<br>                    .providerId(providerId)<br>                    .provider(provider)<br>                    .firstName(appUser.getGivenName())<br>                    .lastName(appUser.getFamilyName())<br>                    .emailVerified(true)<br>                    .profilePictureUrl(appUser.getImageUrl())<br>                    .enabled(true)<br>                    .accountLocked(false)<br>                    .role(Role.USER)<br>                    .version(0)<br>                    .email(appUser.getEmail())<br>                    .build();<br>            user = userRepository.save(userToSave);  // Save the user and assign to userEntity<br>        }<br>        // Check if the user information has changed<br>        boolean updated = false;<br>        if (!user.getFirstName().equals(appUser.getGivenName())) {<br>            user.setFirstName(appUser.getGivenName());<br>            updated = true;<br>        }<br>        if (!user.getLastName().equals(appUser.getFamilyName())) {<br>            user.setLastName(appUser.getFamilyName());<br>            updated = true;<br>        }<br>        if (!user.getProfilePictureUrl().equals(appUser.getImageUrl())) {<br>            user.setProfilePictureUrl(appUser.getImageUrl());<br>            updated = true;<br>        }<br>        if (updated) {<br>            user = userRepository.save(user);<br>        }<br><br>        // Generate JWT token and refresh token<br>        var claims = new HashMap&lt;String, Object&gt;();<br>        claims.put(&quot;fullName&quot;, user.getFullName());<br>        claims.put(&quot;email&quot;, user.getEmail());<br>        String token = jwtService.generateToken(claims, user);<br><br>        // Set the authentication in the context<br>        SecurityContextHolder.getContext().setAuthentication(authentication);<br><br>        // Redirect to the Angular app with the JWT tokens<br>        String redirectUrl = &quot;http://localhost:4200/login/callback&quot;;<br>        redirectUrl += &quot;?accessToken=&quot; + token;<br>        response.sendRedirect(redirectUrl);<br>    }<br><br><br>}</pre><p>The <strong>Oauth2LoginSuccessHandler</strong> class implements AuthenticationSuccessHandler from Spring Security to manage custom actions after a successful OAuth2 login. This interface provides a mechanism to execute specific logic once OAuth2 authentication is completed, seamlessly integrating with the security framework. The onAuthenticationSuccess method carries out several critical functions:</p><ul><li><strong>Extracts User Details</strong>: It retrieves user information from the OAuth2 token. Spring Security automatically populates the authentication object with these details after a successful login, abstracting the complexity of token handling and user data extraction from the OAuth2 provider.</li><li><strong>Manages User Data</strong>: It checks whether the user exists in the database; if not, it creates a new user or updates existing records as necessary. This process ensures that user data is kept up-to-date and accurately reflects the user’s profile.</li><li><strong>Generates JWT</strong>: It generates a JWT token for the authenticated user using the JwtService. This token contains claims about the user and is used to authenticate API requests, facilitating secure communication between the frontend and backend.</li><li><strong>Sets Authentication</strong>: It updates the security context with the user’s authentication details, ensuring that the user’s session and permissions are correctly maintained throughout the application.</li><li><strong>Redirects User</strong>: Finally, it redirects the user to the Angular application, appending the JWT token to the URL. This token is then used by the frontend to authenticate subsequent requests.</li></ul><p>Behind the scenes, the OAuth2 library handles the intricacies of making requests to OAuth2 providers (e.g., Google) and managing the authentication flow. Developers only need to provide the client ID and client secret, while the library takes care of token exchange and user authentication processes. The onAuthenticationSuccess method customizes how user data and tokens are processed and ensures a smooth transition from authentication to application access.</p><p>To test Google Sign-In directly from your backend, use this URL in your browser:<br><a href="http://localhost:9000/api/v1/oauth2/authorization/google"><strong>http://localhost:9000/api/v1/oauth2/authorization/google</strong></a></p><p>Here’s what happens when you access this URL:</p><ul><li><strong>OAuth2 Flow Initiation</strong>: Spring Security starts the OAuth2 authentication process with Google.</li><li><strong>Redirection</strong>: Your browser is redirected to Google’s login page, where you log in and grant permissions.</li><li><strong>Authorization Code Exchange</strong>: Google then redirects back to your application with an authorization code, which Spring Security exchanges for an access token.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vigdY7AeqxtCnuoWtNOkpg.png" /><figcaption>You will see this google sign page after pasting that url</figcaption></figure><p>this is what will be logged in your terminal after successfully login in</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2BTuvM24f5UKToiXorMNuw.png" /></figure><p>If you check your database you will see that the user got successfully added to the database, and you will be redirected to this URL</p><p><strong>http://localhost:4200/login/callback?accessToken=GeneratedToken</strong></p><p>Now all we have to do is initiate the flow not from the browser directly but from the angular application and create the needed components to complete the flow</p><p>Before that tho, Errors always happen so we need to implement a failure handler</p><pre>@Slf4j<br>@Service<br>public class Oauth2LoginFailureHandler implements AuthenticationFailureHandler {<br><br>    @Override<br>    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,<br>                                        AuthenticationException exception) throws IOException, ServletException {<br>        log.error(&quot;Authentication failed: {}&quot;, exception.getMessage());<br>        response.sendRedirect(&quot;http://localhost:4200/login/failure&quot;);<br>    }<br>}</pre><p>This class is basically responsible for logging the error and redirect the user to the login failure page in our frontend</p><h3><strong>Step 4: Implementing the Jwt Filter</strong></h3><pre>package com.demo.social.security;<br><br>/**<br> * JwtFilter is a custom filter that extends OncePerRequestFilter.<br> * It intercepts HTTP requests to validate JWT tokens and set the authentication in the security context.<br> */<br>@Service<br>@Slf4j<br>@RequiredArgsConstructor<br>public class JwtFilter extends OncePerRequestFilter {<br><br>    private final JwtService jwtService;<br>    private final UserRepository userRepository;<br><br>    /**<br>     * Filters incoming HTTP requests to validate JWT tokens.<br>     * If the token is valid, it sets the authentication in the security context.<br>     *<br>     * @param request     the HTTP request<br>     * @param response    the HTTP response<br>     * @param filterChain the filter chain<br>     * @throws ServletException if an error occurs during filtering<br>     * @throws IOException      if an I/O error occurs during filtering<br>     */<br>    @Override<br>    protected void doFilterInternal(@Nonnull HttpServletRequest request, @Nonnull HttpServletResponse response, @Nonnull FilterChain filterChain) throws ServletException, IOException {<br>        // Skip filtering for authentication endpoints<br>        if (request.getServletPath().contains(&quot;/api/v1/auth&quot;)) {<br>            filterChain.doFilter(request, response);<br>            return;<br>        }<br><br>        final String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);<br>        final String jwt;<br>        final String id;<br><br>        // If the authorization header is missing or does not start with &quot;Bearer &quot;, skip filtering<br>        if (authorizationHeader == null || !authorizationHeader.startsWith(&quot;Bearer &quot;)) {<br>            filterChain.doFilter(request, response);<br>            return;<br>        }<br><br>        // Extract JWT token from the authorization header<br>        jwt = authorizationHeader.substring(7);<br>        id = jwtService.extractUsername(jwt);<br><br>        // If the user email is not null and the security context does not already have an authentication, proceed with validation<br>        if (id != null &amp;&amp; SecurityContextHolder.getContext().getAuthentication() == null) {<br>            UserDetails userDetails = userRepository.findById(UUID.fromString(id)).orElseThrow(<br>                    () -&gt; new NotFoundException(NotFoundException.NotFoundExceptionType.USER_NOT_FOUND, id)<br>            );<br><br><br>            // If the token is valid, set the authentication in the security context<br>            if (jwtService.isTokenValid(jwt, userDetails)) {<br>                UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(<br>                        userDetails,<br>                        null,<br>                        userDetails.getAuthorities()<br>                );<br>                authToken.setDetails(<br>                        new WebAuthenticationDetailsSource().buildDetails(request)<br>                );<br>                SecurityContextHolder.getContext().setAuthentication(authToken);<br>            }else{<br>                throw new InvalidException(InvalidException.InvalidExceptionType.TOKEN_INVALID);<br>            }<br>        }<br><br>        // Continue with the filter chain<br>        filterChain.doFilter(request, response);<br>    }<br>}</pre><p>The JwtFilter class is a custom filter that extends OncePerRequestFilter to manage JWT token validation in Spring Security. After a successful Google login, the backend generates a JWT token, which must be included in the Authorization header of subsequent requests.</p><p>Here’s what the JwtFilter does:</p><ul><li><strong>Token Extraction</strong>: Extracts the JWT token from the Authorization header of incoming requests.</li><li><strong>Validation</strong>: Uses JwtService to validate the token and checks if it corresponds to a user in the database.</li><li><strong>Authentication Setting</strong>: If the token is valid, it sets the authenticated user in the Spring Security context, allowing access to protected resources.</li><li><strong>Exception Handling</strong>: Throws exceptions for invalid tokens or missing users.</li></ul><h3>Step 5: Implementing the Frontend with Angular</h3><p>Now to the awaited part, How to integrate what we have done so far with our frontend application</p><p><strong>1. Create a New Angular Project:</strong></p><ul><li>First, ensure you have Angular CLI installed. If not, install it using:</li></ul><pre>npm install -g @angular/cli</pre><p>Create a new Angular project using the Angular CLI:</p><p>Make sure to answer No when angular CLI asks whether you want to support ssr in your application</p><pre>ng new social-demo</pre><p>Navigate to your project directory:</p><pre>cd social-demo</pre><p><strong>2. Generate Components, guards, environment folder, and interceptors:</strong></p><pre>ng generate component login<br>ng generate component loginCallback<br>ng generate component loginFailure<br>ng generate component home<br>ng generate service user<br>ng generate interceptor auth<br>ng generate guard Auth<br>ng generate guard NoAuth</pre><p>Setup the app.routes.ts</p><pre>import { Routes } from &#39;@angular/router&#39;;<br>import { LoginComponent } from &#39;./login/login.component&#39;;<br>import { LoginCallbackComponent } from &#39;./login-callback/login-callback.component&#39;;<br>import { HomeComponent } from &#39;./home/home.component&#39;;<br>import { AuthGuard } from &#39;./auth/guards/AuthGuard/auth.guard&#39;;<br>import { noAuthGuard } from &#39;./auth/guards/noAuthGuard/no-auth.guard&#39;;<br>import { LoginFailureComponent } from &#39;./login-failure/login-failure.component&#39;;<br><br>export const routes: Routes = [<br>  {<br>    path: &#39;&#39;,<br>    redirectTo: &#39;login&#39;,<br>    pathMatch: &#39;full&#39;,<br>  },<br>  {<br>    canActivate: [noAuthGuard],<br>    path: &#39;login&#39;,<br>    component: LoginComponent,<br>    children: [<br>      { path: &#39;callback&#39;, component: LoginCallbackComponent },<br>      { path: &#39;failure&#39;, component: LoginFailureComponent },<br>    ],<br>  },<br><br>  {<br>    canActivate: [AuthGuard],<br>    path: &#39;home&#39;,<br>    component: HomeComponent,<br>  },<br>];</pre><p>Setup the environment.development.ts</p><pre>export const environment = {<br>  googleClientId:<br>    &#39;YourClientId&#39;,<br>  loginUri: &#39;http://localhost:9000/api/v1/oauth2/authorization/google?token=&#39;,<br>  apiUrl: &#39;http://localhost:9000/api/v1&#39;,<br>};</pre><p><strong>3. Set Up the Google Login-in Component:</strong></p><p>login.component.html</p><pre>&lt;div class=&quot;flex flex-col gap-3 items-center justify-center h-screen w-screen&quot;&gt;<br>  Social login demo with Spring Boot and Angular<br>  &lt;!-- The Google login button will be rendered from the TypeScript file using Renderer2.<br>         This is necessary because the button needs to be rendered after the view is initialized.<br>         Additionally, the Google script loads only once, so it must be reloaded each time the login component is initialized.<br>    --&gt;<br><br>  &lt;div class=&quot;max-w-4xl&quot; #googleButton&gt;&lt;/div&gt;<br>&lt;/div&gt;<br>&lt;!-- The router-outlet is needed to render child routes.<br>       Without it, /login/callback won&#39;t work because /callback is a child route of /login.<br>  --&gt;<br>&lt;router-outlet&gt;&lt;/router-outlet&gt;</pre><p>login.component.ts</p><pre>import {<br>  Component,<br>  ElementRef,<br>  ViewChild,<br>  Renderer2,<br>  AfterViewInit,<br>} from &#39;@angular/core&#39;;<br><br>import { RouterModule } from &#39;@angular/router&#39;;<br>import { CommonModule } from &#39;@angular/common&#39;;<br>import { environment } from &#39;../../environments/environment.development&#39;;<br><br>@Component({<br>  selector: &#39;login-root&#39;,<br>  standalone: true,<br>  imports: [CommonModule, RouterModule],<br>  templateUrl: &#39;./login.component.html&#39;,<br>})<br>export class LoginComponent implements AfterViewInit {<br>  // ViewChild decorator to get a reference to the Google Sign-In button element<br>  @ViewChild(&#39;googleButton&#39;) gbutton: ElementRef = new ElementRef({});<br>  <br>  // Injecting Renderer2 for DOM manipulation<br>  constructor(private renderer: Renderer2) {}<br><br>  // Lifecycle hook that is called after the component&#39;s view has been fully initialized<br>  ngAfterViewInit() {<br>    this.addGoogleSignInScript();<br>  }<br><br>  // Method to add the Google Sign-In script to the document<br>  addGoogleSignInScript(): void {<br>    const script = this.renderer.createElement(&#39;script&#39;);<br>    script.src = &#39;https://accounts.google.com/gsi/client&#39;;<br>    script.async = true;<br>    script.defer = true;<br>    script.onload = () =&gt; this.initializeGoogleSignIn();<br>    this.renderer.appendChild(document.body, script);<br>  }<br><br>  // Method to initialize Google Sign-In after the script is loaded<br>  initializeGoogleSignIn(): void {<br>    const clientId = environment.googleClientId;<br>    // Initialize Google Sign-In with the client ID and other options<br>    // @ts-ignore<br>    window.google.accounts.id.initialize({<br>      client_id: clientId,<br>      itp_support: true,<br>      ux_mode: &#39;popup&#39;,<br>      context: &#39;signin&#39;,<br>      callback: this.handleCredentialResponse.bind(this),<br>    });<br>    // Render the Google Sign-In button<br>    // @ts-ignore<br>    window.google.accounts.id.renderButton(this.gbutton.nativeElement, {<br>      type: &#39;standard&#39;,<br>      theme: &#39;filled_blue&#39;,<br>      size: &#39;large&#39;,<br>      shape: &#39;pill&#39;,<br>    });<br>    // Prompt the user to sign in<br>    // @ts-ignore<br>    window.google.accounts.id.prompt();<br>  }<br><br> // Callback method to handle the credential response from Google Sign-In<br>// Initially, we would directly call the backend endpoint: http://localhost:9000/api/v1/oauth2/authorization/google<br>// Now, with the frontend in place, we need to pass the token-id we received from Google<br>// to our backend. This URL is constructed with the token-id as a query parameter, allowing the backend to validate it.<br>handleCredentialResponse(response: any): void {<br>  window.location.href = `${environment.loginUri}${response.credential}`;<br>}<br>  handleCredentialResponse(response: any): void {<br>    window.location.href = `${environment.loginUri}${response.credential}`;<br>  }<br>}</pre><p>You can style the Google login button like you want, following this Google guide,</p><p><a href="https://developers.google.com/identity/gsi/web/reference/html-reference#element_with_class_g_id_signin">https://developers.google.com/identity/gsi/web/reference/html-reference#element_with_class_g_id_signin</a></p><p>just change the attributes here :</p><pre>window.google.accounts.id.renderButton(this.gbutton.nativeElement, {<br>      type: &#39;standard&#39;<br>      theme: &#39;filled_blue&#39;,<br>      size: &#39;large&#39;,<br>      shape: &#39;pill&#39;,<br>    });</pre><p><strong>4. Set Up the Login-callback Component:</strong></p><p>The LoginCallbackComponent handles the redirection from the backend after a successful OAuth2 login. It extracts the access token from the query parameters, saves it in local storage, and navigates the user to the home page. If the token is missing, it redirects to a failure page. This component ensures proper handling of the token and user redirection after authentication.</p><p>Keep in mind that after a successful login, we redirect to<br><strong>http://localhost:4200/login/callback?accessToken=GeneratedToken</strong><br>so basically we are redirecting to this component.</p><pre>import { Component, inject, OnInit } from &#39;@angular/core&#39;;<br>import { ActivatedRoute, Router } from &#39;@angular/router&#39;;<br><br>@Component({<br>  selector: &#39;app-login-callback&#39;,<br>  standalone: true,<br>  imports: [],<br>  templateUrl: &#39;./login-callback.component.html&#39;,<br>})<br>export class LoginCallbackComponent implements OnInit {<br>  accessToken: string = &#39;&#39;;<br>  private readonly activatedRoute = inject(ActivatedRoute);<br>  private readonly router = inject(Router);<br><br>  ngOnInit(): void {<br>    // get the access token from the query params<br>    this.accessToken = this.activatedRoute.snapshot.queryParams[&#39;accessToken&#39;];<br>    // if the access token is present, store it in the local storage and navigate to the home page<br>    if (this.accessToken) {<br>      localStorage.setItem(&#39;accessToken&#39;, this.accessToken);<br>      this.router.navigate([&#39;/home&#39;]);<br>    } else {<br>      this.router.navigate([&#39;/login/failure&#39;]);<br>      console.error(&#39;Tokens are missing&#39;);<br>    }<br>  }<br>}</pre><blockquote>The login failure component will just be a simple component that shows an error message</blockquote><p><strong>5. Set Up the User model and service:</strong></p><p>User.ts</p><pre>export interface User {<br>  id?: string;<br>  email: string;<br>  firstName: string;<br>  lastName: string;<br>  phoneNumber: string;<br>  profilePictureUrl: string;<br>  emailVerified: boolean;<br>  enabled: boolean;<br>  createdAt: Date;<br>  updatedAt: Date;<br>  provider: string;<br>  providerId: string;<br>}<br></pre><p>user.service.ts</p><pre>import { inject, Injectable } from &#39;@angular/core&#39;;<br>import { environment } from &#39;../../environments/environment.development&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { Observable, ReplaySubject, tap } from &#39;rxjs&#39;;<br>import { User } from &#39;../model/User&#39;;<br><br>/**<br> * UserService is responsible for managing user-related operations such as fetching user data<br> * and checking if a user is present. It uses Angular&#39;s HttpClient to make HTTP requests and<br> * RxJS&#39;s ReplaySubject to manage user state.<br> */<br>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class UserService {<br>  // Base URL for user-related API endpoints<br>  private apiUrl = `${environment.apiUrl}/user`;<br><br>  // Injecting HttpClient for making HTTP requests<br>  private readonly httpClient = inject(HttpClient);<br><br>  // ReplaySubject to hold the user data and allow subscribers to receive the latest user data<br>  private user_: ReplaySubject&lt;User&gt; = new ReplaySubject&lt;User&gt;(1);<br><br>  /**<br>   * Getter for the user observable.<br>   * @returns {Observable&lt;User&gt;} An observable that emits the current user data.<br>   */<br>  get user(): Observable&lt;User&gt; {<br>    return this.user_.asObservable();<br>  }<br><br>  /**<br>   * Setter for the user.<br>   * @param {User} value - The user data to set.<br>   */<br>  set user(value: User) {<br>    this.user_.next(value);<br>  }<br><br>  /**<br>   * Fetches the current user data from the API.<br>   * @returns {Observable&lt;User&gt;} An observable that emits the fetched user data.<br>   */<br>  getUser(): Observable&lt;User&gt; {<br>    return this.httpClient.get&lt;User&gt;(`${this.apiUrl}/me`).pipe(<br>      tap((user: User) =&gt; {<br>        this.user = user; // Update the user data in the ReplaySubject<br>      })<br>    );<br>  }<br><br>  /**<br>   * Checks if the user data is present in the ReplaySubject.<br>   * @returns {boolean} True if user data is present, false otherwise.<br>   */<br>  hasUser(): boolean {<br>    let hasValue = false;<br>    this.user_<br>      .subscribe({<br>        next: () =&gt; {<br>          hasValue = true;<br>        },<br>        error: () =&gt; {<br>          hasValue = false;<br>        },<br>        complete: () =&gt; {<br>          hasValue = false;<br>        },<br>      })<br>      .unsubscribe();<br>    return hasValue;<br>  }<br>}</pre><p><strong>6. Set Up the Home component:</strong></p><p>home.component.ts</p><pre>@if(user){<br>&lt;div<br>  class=&quot;flex flex-col items-center justify-center bg-gray-100 p-6 rounded-lg shadow-lg&quot;<br>&gt;<br>  &lt;h1 class=&quot;text-3xl font-bold mb-4&quot;&gt;Home&lt;/h1&gt;<br>  &lt;img<br>    [src]=&quot;user.profilePictureUrl&quot;<br>    alt=&quot;Profile pic&quot;<br>    class=&quot;rounded-full h-36 w-36 mb-4 border-4 border-gray-300&quot;<br>  /&gt;<br>  &lt;p class=&quot;text-lg mb-2&quot;&gt;<br>    Welcome to the home page!<br>    &lt;span class=&quot;font-bold text-blue-600&quot;<br>      &gt;{{ user.firstName }} {{ user.lastName }}&lt;/span<br>    &gt;<br>  &lt;/p&gt;<br>  &lt;p class=&quot;text-lg mb-2&quot;&gt;<br>    You are currently logged in with<br>    &lt;span class=&quot;font-bold text-green-600&quot;&gt;{{ user.provider }}&lt;/span&gt;<br>  &lt;/p&gt;<br>  &lt;p class=&quot;text-lg mb-2&quot;&gt;<br>    Email: &lt;span class=&quot;font-bold&quot;&gt;{{ user.email }}&lt;/span&gt;<br>  &lt;/p&gt;<br>  &lt;p class=&quot;text-lg mb-2&quot;&gt;<br>    Email Verified:<br>    &lt;span class=&quot;font-bold&quot;&gt;{{ user.emailVerified ? &quot;Yes&quot; : &quot;No&quot; }}&lt;/span&gt;<br>  &lt;/p&gt;<br>  &lt;p class=&quot;text-lg mb-2&quot;&gt;<br>    Account Enabled:<br>    &lt;span class=&quot;font-bold&quot;&gt;{{ user.enabled ? &quot;Yes&quot; : &quot;No&quot; }}&lt;/span&gt;<br>  &lt;/p&gt;<br>  &lt;p class=&quot;text-lg mb-2&quot;&gt;<br>    Account Created At:<br>    &lt;span class=&quot;font-bold&quot;&gt;{{ user.createdAt | date : &quot;medium&quot; }}&lt;/span&gt;<br>  &lt;/p&gt;<br>  &lt;p class=&quot;text-lg mb-2&quot;&gt;<br>    Last Updated At:<br>    &lt;span class=&quot;font-bold&quot;&gt;{{ user.updatedAt | date : &quot;medium&quot; }}&lt;/span&gt;<br>  &lt;/p&gt;<br>&lt;/div&gt;<br><br>}@else {<br>&lt;div<br>  class=&quot;flex flex-col items-center justify-center bg-gray-100 p-6 rounded-lg shadow-lg&quot;<br>&gt;<br>  loading...<br>&lt;/div&gt;<br>}</pre><p>home.component.ts</p><pre>import { Component, inject, OnInit } from &#39;@angular/core&#39;;<br>import { UserService } from &#39;../service/user.service&#39;;<br>import { User } from &#39;../model/User&#39;;<br>import { CommonModule } from &#39;@angular/common&#39;;<br><br>@Component({<br>  selector: &#39;app-home&#39;,<br>  standalone: true,<br>  imports: [CommonModule],<br>  templateUrl: &#39;./home.component.html&#39;,<br>  styleUrl: &#39;./home.component.css&#39;,<br>})<br>export class HomeComponent implements OnInit {<br>  user: any;<br>  private readonly userService = inject(UserService);<br><br>  ngOnInit(): void {<br>    this.userService.user.subscribe({<br>      next: (user: User) =&gt; {<br>        this.user = user;<br>      },<br>      error: (error) =&gt; {<br>        console.error(error);<br>      },<br>    });<br>  }<br>}</pre><p><strong>7. Set Up the auth guards and interceptors:</strong></p><p>auth.interceptor.ts</p><pre>import { HttpInterceptorFn } from &#39;@angular/common/http&#39;;<br><br>export const authInterceptor: HttpInterceptorFn = (req, next) =&gt; {<br>  // Clone the request to add the new header.<br>  let newReq = req;<br>  const accessToken = localStorage.getItem(&#39;accessToken&#39;);<br><br>  if (accessToken) {<br>    // Add the Authorization header with the token.<br>    newReq = req.clone({<br>      headers: req.headers.set(&#39;Authorization&#39;, `Bearer ${accessToken}`),<br>    });<br>  }<br><br>  return next(newReq);<br>};</pre><p>auth.guard.ts</p><pre>import { CanActivateFn, Router } from &#39;@angular/router&#39;;<br>import { inject } from &#39;@angular/core&#39;;<br>import { UserService } from &#39;../../../service/user.service&#39;;<br><br>export const AuthGuard: CanActivateFn = (route, state) =&gt; {<br>  const token = localStorage.getItem(&#39;accessToken&#39;);<br>  const userService = inject(UserService);<br>  const router = inject(Router);<br>  // If the token is missing, redirect to the login page.<br>  if (!token) {<br>    router.navigate([&#39;/login&#39;]);<br>    return false;<br>  }<br><br>  // If the user is missing, fetch the user.<br>  if (!userService.hasUser()) {<br>    userService.getUser().subscribe();<br>  }<br>  return true;<br>};</pre><p>no-auth.guard.ts</p><pre>import { inject } from &#39;@angular/core&#39;;<br>import { CanActivateFn, Router } from &#39;@angular/router&#39;;<br><br>export const noAuthGuard: CanActivateFn = (route, state) =&gt; {<br>  const token = localStorage.getItem(&#39;accessToken&#39;);<br>  const router = inject(Router);<br>  // If the token is present, redirect to the home page.<br>  if (token) {<br>    router.navigate([&#39;/home&#39;]);<br>    return false;<br>  }<br>  return true;<br>};</pre><ul><li><strong>AuthGuard</strong>: Ensures that only authenticated users can access specific routes. It checks if the user is logged in before granting access to protected pages, redirecting unauthenticated users to the login page.</li><li><strong>NoAuthGuard</strong>: Prevents authenticated users from accessing certain routes, such as the login page, to avoid redundant or unauthorized access. It ensures that logged-in users are redirected away from routes meant for unauthenticated users.</li><li><strong>HTTP Interceptors</strong>: Automatically attach authentication tokens to outgoing HTTP requests. This ensures secure communication with the backend by including the JWT token in the request headers, streamlining authentication and authorization processes.</li></ul><p><strong>We will end up with this result</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*5faRhPz2wzBaETpnUFekVw.png" /></figure><p>The user successfully signed in with Google, the accessToken is saved in local storage and the user is saved in our DBYou can find the source good in this GitHub repo:<br><a href="https://github.com/Oussemasahbeni/spring-boot-angualr-social-login-tutorial">https://github.com/Oussemasahbeni/spring-boot-angualr-social-login-tutorial</a></p><h3>Final Thoughts</h3><p>This article provides a thorough overview of integrating Google social login into your application using Angular and Spring Boot. The guide covers everything from setting up OAuth 2.0 credentials in the Google Developer Console to configuring both the backend and frontend to manage user authentication. By following these steps, and filling in the provided placeholders with code from your repository, you’ll be able to offer a secure and user-friendly social login experience in your application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=344ae8178a8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>