-
Notifications
You must be signed in to change notification settings - Fork 279
Chapter: Authentication
Here is the complete workflow of the Google SSO Authentication.
This will be the most preferable way to set up authentication in the RocketChat component for any production application. For setting up Google sign-in into RocketChat instance, (as almost everyone uses a Gmail account and it is just a click to sign in or signup) we need to configure Google OAuth in RocketChat.
This process will need us to set up a Google OAuth App in Google’s developer console. For setting up Google SSO in the RocketChat component, we need to get the CLIENT_ID as props from the RocketChat component user and everything else will be handled in the EmbeddedChat component itself.
How you may ask?
When we click on “Login with Google” in EmbeddedChat we will receive the idToken and accessToken from google which we can use to authenticate the user using RocketChat’s Login with Google endpoint, as we require only those two parameters. And we will be getting a user response back from the RocketChat server from which rc_token
and rc_uid
can be extracted and we are good to go in making API calls and requests.
Note: We need to turn off the TOTP feature to make this work. Go to Admin -> Accounts -> Two Factor Authentication
disable it.
Why? Because after we log in with Google and we get the tokens and call the RC Google Auth endpoint we will get an error saying TOTP error. Can we fix this? Yes, but we need the user's email and password to make this call. But, Google doesn't provide us with the password.
Provide the Client Id,
<RCComponent
GOOGLE_CLIENT_ID={"your-google-client-id"}
/>
This function will get us the accessToken
and idToken
.
// src/hooks/useGoogleLogin.js
const signIn = async () => {
const auth = await gapi.auth2.getAuthInstance();
await auth.signIn();
const { access_token, id_token } = await auth.currentUser
.get()
.getAuthResponse();
return { access_token, id_token };
};
Then we need to use them to sign in to the Rocket.Chat instance.
// src/lib/api.js
async googleSSOLogin(signIn) {
const tokens = await signIn();
try {
const req = await fetch(`${this.host}/api/v1/login`, {
...
body: JSON.stringify({
serviceName: 'google',
accessToken: tokens.access_token,
idToken: tokens.id_token,
expiresIn: 3600,
}),
});
...
After this step, we need to know if the user has an account already in RocketChat or not because RocketChat after successful signup asks for the user's username. So we need to check if the user already has a username, if so we can just return from there else we need to set the username for the user.
async updateUserUsername(userid, username) {
let newUserName = username.replace(/\s/g, '.').toLowerCase(); // same as of RocketChat's username suggestion property
...
}
After that, we will successfully populate the rc_token
and rc_uid
and we are ready to work with other API calls.