How to use a FireBase as a Auth provider (untested)¶
Angular¶
Install firebase to angular
Initialize firebase in Angular app
import { initializeApp } from "firebase/app";
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID",
};
const app = initializeApp(firebaseConfig);
Log user in
import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
const auth = getAuth();
const provider = new GoogleAuthProvider();
signInWithPopup(auth, provider)
.then((result) => {
const user = result.user;
console.log("User signed in:", user);
})
.catch((error) => {
console.error("Error during sign-in:", error);
});
Send the id to SpringBoot
const user = auth.currentUser;
if (user) {
user.getIdToken().then((idToken) => {
// Send idToken to backend for verification
this.http.post('/api/authenticate', { token: idToken }).subscribe();
});
}
SpringBoot¶
Configure Firebase Admin SDK dependency
<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>8.1.0</version>
</dependency>
Initialize Firebase in SpringBoot
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.auth.oauth2.GoogleCredentials;
@PostConstruct
public void initFirebase() {
FirebaseOptions options = FirebaseOptions.builder()
.setCredentials(GoogleCredentials.fromStream(new FileInputStream("path/to/serviceAccountKey.json")))
.build();
FirebaseApp.initializeApp(options);
}
Verify the token in a controller
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseToken;
@PostMapping("/api/authenticate")
public ResponseEntity<?> authenticate(@RequestBody Map<String, String> body) {
try {
String idToken = body.get("token");
FirebaseToken decodedToken = FirebaseAuth.getInstance().verifyIdToken(idToken);
String uid = decodedToken.getUid();
// Perform additional logic (e.g., store/retrieve user data from MySQL)
return ResponseEntity.ok("User authenticated: " + uid);
} catch (FirebaseAuthException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid token");
}
}