Authorization with OAuth2 Class in Wijmo
The samples from these recent articles use the OAuth2 component to perform client authentication.
- Using Google Sheets with Wijmo
- Realtime Firestore Updates with Wijmo Snapshot Class
- Using Firestore Databases with Wijmo
The OAuth2 component is a thin wrapper for Google's GAPI library. To use the OAuth2 class, create an instance of it passing in the following parameters:
- API_KEY: A key that identifies the calling app. It is used for authentication with APIs that do not access personal data. API keys typically restrict the domains that are authorized to use them and the scopes.
- CLIENT_ID: A key that identifies the Google Account that owns the resources that the app will use.
- SCOPES: An array containing strings that define the authorizations the app needs (for example, accessing Google Sheets, Firestore databases, or files on Google Drive).
Using the Authorization Class in JavaScript Applications
Once the OAuth2 class is created, you can:
- Call the signIn and signOut methods to sign in or out of the application,
- Listen to the userChanged event to find out if a user just logged in or out,
- Read the user property to determine if a user is logged in, and
- Get the current user's accessToken so it can be used in server calls that require authentication.
For example, this is how the samples we discussed earlier use the OAuth2 class:
// instantiate the OAuth2 class
const SCOPES = [ '[https://www.googleapis.com/auth/userinfo.email](https://www.googleapis.com/auth/userinfo.email)' ]
let auth = new OAuth2(API_KEY, CLIENT_ID, SCOPES);
// click button to log user in or out
oAuthBtn.addEventListener('click', () => {
if (auth.user) {
auth.signOut();
} else {
auth.signIn();
}
});
// update button/sheet state when user changes
auth.userChanged.addHandler(s => {
// update button caption
let user = s.user;
oAuthBtn.textContent = user ? 'Sign Out' : 'Sign In';
// update GoogleSheet and Firestore access token
gsNWind.accessToken = user ? s.accessToken : null;
fsNWind.accessToken = user ? s.accessToken : null;
});
As you can see, the OAuth2 class makes user authentication very easy to use. But under the covers, it is the GAPI library and Google's OAuth services that are doing all the heavy lifting.
The main service we get from the OAuth2 class is the accessToken string that the GoogleSheets and Firestore classes need for authorization. If you want to use other authorization services that can provide the access tokens, you don't need the OAuth2 class.