This time is a continuation of this article. Implementation of Google Sign-In using Google OAuth 2.0 authentication (JS edition) It's like logging in on the client side and authenticating on the backend server.
In the previous article, I was able to get user information etc. in the response. However, it is dangerous to send this to the server side as it is. For example, you can impersonate a user when sending a user ID to the server. ..
So instead, use a verifiable ID token to securely retrieve user information signed in on the server side.
Let's implement it right away.
First, rewrite the JS part.
JavaScript
function onSignIn(googleUser) {
var id_token = googleUser.getAuthResponse().id_token; //Get ID token
//Process of sending ID token to server side
}
I think that there are various ways to send to the server side here, such as using Ajax or sending with the hidden attribute. This time, we will communicate with the server by issuing an HTTP request using Ajax's XMLHttpRequest.
In addition to the previous process
javaScript
var req = new XMLHttpRequest();
req.open('POST', '[URL]’);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.onload = function() {
req.send('idtoken=' + id_token);
Let's send it to the server side like this. *** Enter the server-side URL in the [URL] *** part.
This time, we will implement it using Java Spring boot.
First, add a dependency.
build.gradle
dependencies {
implementation("com.google.api-client:google-api-client:1.30.5")
}
You can easily verify your ID token using the Google Client Library.
Java
GoogleIdTokenVerifier verifier =
new GoogleIdTokenVerifier.Builder(
new NetHttpTransport(), JacksonFactory.getDefaultInstance())
.setAudience(Collections.singletonList("YOUR_CLIENT_ID.apps.googleusercontent.com"))
.build();
var idtokenStriing = getIdToken(); //Obtained ID token
GoogleIdToken idToken = verifier.verify(idTokenString); //ID token verification
Enter your client ID in YOUR_CLIENT_ID.
If you do not use the Google client library, you can use Google's public key (PEM format) to verify the token signature, but Google also recommends using the Google client library to verify it. Let's use it.
All you have to do is get the user information.
Java
Payload payload = idToken.getPayload();
String userId = payload.getSubject(); //User ID
String email = payload.getEmail(); //User email address
String name = (String) payload.get("name"); //username
String pictureUrl = (String) payload.get("picture"); //User profile image
You can get it like this.
Nowadays, more and more sites are using OAuth authentication. This time it is Google, but I will also give OAuth authentication such as Facebook and Apple.
Recommended Posts