Java Programming

Java Spring Boot Google SignIn

Register ClientId and ClientSecret

Để tạo ClientId và ClientSecret trong Google Console ta thực hiện theo các bước sau:

B1: Truy cập vào link https://console.cloud.google.com/apis/credentials

B2: Chọn CREATE CREDENTIALS

B3: chọn OAuth client ID

B4: chọn Web Application

B5: rồi nhập Authorized JavaScript origins với url là đường dẫn của hosting ví dụ: http://ceb.net.vn

B6: Authorized redirect URIs là url của hosting ví dụ http://ceb.net.vn/login/oauth2/code/google

B7: Sau cùng ta chọn Save để lấy ClientId và ClientSecret

Configuration ClientId and ClientSecret

spring.security.oauth2.client.registration.google.client-id=27989302874-7f9fnlfq3g7eo1pblbhgt39pt16ftds8.apps.googleusercontent.com
spring.security.oauth2.client.registration.google.client-secret=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

Install package Authentication Google

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity6</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <scope>test</scope>
</dependency>

Security Config

Create class Security Config in main Program with following

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
        http.authorizeHttpRequests(p -> p.requestMatchers("/", "/auth/login").permitAll().anyRequest().authenticated())
            .oauth2Login(p -> p.defaultSuccessUrl("/auth/googleresponse"))
            .logout(p -> p.logoutUrl("/auth/logout").logoutSuccessUrl("/auth/login"));
        return http.build();
    }
}

Login with Google

<a href="/oauth2/authorization/google">Login with Google</a>

Google Response

In google response with key sub, given_name, family_name, name, email

Map<String, Object> map = user.getAttributes();
String email = map.get("email").toString();
String id = map.get("sub");
String givenName = map.get("given_name");
String familyName = map.get("family_name");
String name = map.get("name");

Show Attributes

<p th:if="${param.success}">Login Success</p>
<p>Name: <span th:text="${#authentication.principal.attributes['name']}"></span></p>
<p>Email: <span th:text="${#authentication.principal.attributes['email']}"></span></p>

Show Login and Logout

<li sec:authorize="!isAuthenticated()"><a href="/auth/login">Login</a></li>
<li sec:authorize="isAuthenticated()">
    <form th:action="@{/auth/logout}" method="post">
        <button>Logout</button>
    </form>
</li>