Friday, February 10, 2023

Spring Security identity extraction from Google Cloud IAP or Firebase headers

 

Spring Security is a framework that provides authentication and authorization services to applications. With the rise of cloud-based services, security has become even more important. In this blog post, we will focus on how to extract the identity of a user from the headers provided by Google Cloud IAP or Firebase.

Google Cloud IAP (Identity-Aware Proxy) is a service that provides secure access to applications running on Google Cloud Platform. Firebase is a mobile and web application development platform that provides a range of tools and services to build, deploy, and scale applications. Both of these services provide headers with user identity information that can be used by Spring Security to authenticate and authorize users.

To extract the identity from the headers, we first need to configure the security configuration in our application. In the security configuration class, we can use the following code to extract the headers from the request:

@Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest() .authenticated() .and() .oauth2Login() .userInfoEndpoint() .userService(new UserInfoUserService(header -> { String email = header.get("X-Goog-Authenticated-User-Email"); return new User(email, "", new ArrayList<>()); })); }

The UserInfoUserService class is a custom implementation of UserDetailsService that retrieves the user information from the headers. The header parameter in the UserInfoUserService constructor is a Map that contains the headers from the request. In this example, we are using the X-Goog-Authenticated-User-Email header to extract the email of the user.

For Firebase, we can use the following code in our security configuration:

@Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest() .authenticated() .and() .oauth2Login() .userInfoEndpoint() .userService(new UserInfoUserService(header -> { String uid = header.get("X-Firebase-UID"); return new User(uid, "", new ArrayList<>()); })); }

In this example, we are using the X-Firebase-UID header to extract the user identifier from Firebase.

In conclusion, extracting the identity from the headers provided by Google Cloud IAP or Firebase is a simple process that can be achieved by using a custom implementation of UserDetailsService. With this information, Spring Security can authenticate and authorize users based on the headers provided by these services.


No comments:

Post a Comment