Front End Integration

Wink Login SDK can be integrated in your application front end using our Javascript SDK. This page describes the steps to be followed:

Step1: Add a Wink Sign-In button

It is possible to add a "Sign-In with Wink" button to allow your users to access your app or website using Wink Login's MFA. This button should be placed alongside your other sign-in methods ( if your app offers multiple ways to sign-in).

With only a few lines of code, you can add a button that automatically configures itself to have the appropriate text, logo, and colors for the sign-in state of the user and the scopes you request.

📘

Button Styling

The Wink Button styling as well as the images can be found here in the public folder and images can be found here under public/assets folder:

Wink button images

Additionally, Wink's button styling examples can be found here:

Wink button styles

The above button styles and info can be used to test the sample code below

<button id="wink-oauth-button" class="wink-oauth-button-light">
  <img src="semicolon-white.svg" /> 
  Login with Wink
</button>

Step 2: Add the Wink Login component to your webpage or app

The easiest way to add the Wink Login component to your site is to use an automatically rendered component provided by Wink. With only a few lines of code, you can add this code that automatically configures itself to have the appropriate camera and microphone permissions, the user's sign-in state, and the scopes you request.
To create a Wink Login component that uses the default settings, add the below Javascript to your sign-in page:

<script src="winklogin.module.js"></script> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

🚧

Files Required

  • The winklogin.module.js file
    must be stored in the root directory to ensure wink is loaded properly. The file can be found in the code section of the link below, go to public folder, the winklogin.module.js file will be there. please continue on this link here to access the file
  • The silent-check-sso.html file
    In order for Oauth to function properly, this file must be placed in the root directory. This file must contain the below tag and can be found under public folder here
<html><body><script>parent.postMessage(location.href,location.origin)</script></body></html>

Step 3: Configure, initialize and call Wink Login

The following code block shows how to call Wink Login when user clicks the Sign-in button. The code below also waits for Wink Login to complete, retrieves the access token and parses it to display it. In your own code however you just need to retrieve the access token and send it to your server for validation.

<script>
const clientId = 'stage-winkwallet';
// Client’s configuration
var config = {
    url: 'https://stagekeycloak.winklogin.com',
    realm: 'wink',
    clientId,
    onAuthErrorFailure: (error) => console.error(error),
    loggingEnabled: true,
};
const winkLoginClient = getWinkLoginClient(config);
var refreshButtonInterval;
window.addEventListener('load', (event) => {
    // Initialization of wink login with callback functions
    winkLoginClient.winkInit({
        onFailure: (error) => console.error(error),
        onSuccess: winkLoadUserProfile,
    });
    // Initialization of login button onclick function
    const loginButton = document.getElementById('wink-oauth-button');
    loginButton.addEventListener('click', () => {
        winkLoginClient.winkLogin({
            onFailure: (error) => console.error(error),
        });
    });
});
function winkLoadUserProfile() {
          const data = parseJwt(winkLoginClient.token);
          data['username'] = data.username ?? data.preferred_username;
          
          // for displaying the user data 
          renderUserData(winkLoginClient, data);
         
      }

function renderUserData(winkLoginKeycloak, profile) {
        let userDataElement = document.getElementById('wink-user-data');
        if (userDataElement) {
          userDataElement.innerHTML = '';
          userDataElement.innerHTML = `
      `;
          renderButtons();
          renderTokens(profile);
        } else {
          console.warn('no element with ID #wink-user-data found');
        }
      }
 function parseJwt(token) {
        var base64Url = token.split('.')[1];
        var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
        var jsonPayload = decodeURIComponent(
          window
            .atob(base64)
            .split('')
            .map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
            .join('')
        );
        return JSON.parse(jsonPayload);
      }

</script>

👍

Note: The ClientID shown in the code block above (“stage-winkwallet”) should be replaced by the ClientID provided for your application in your Wink Login welcome packet.


Step 4: Login Session Management

📘

Once Wink Login SDK redirects user back to your app with the OAUTH2 tokens, it is your responsibility to manage the login session. As default ( not changeable in this release of Wink Login ), the ID Token and Access Token are valid for 5 min each and Refresh Token is valid for 30 min

using the Access Token to handle logged in state

Your application that integrates Wink Login has to manage its own login state as if you were using username and password or another login mechanism like Google sign-in. Once user is logged in and you should confirm its validity by sending the token to your server (see Validating Access Token). You must set login state of the user as true on your side once token validation is a success.

Once user click logout you should call the sign-out code (see below) set login state as logged out on your server. When the user revisits your login page, you check login state on your server and display login button or user name depending on your own login state. When access token is about to expire you should ask user if they want to continue session or not. If user clicks continue call refresh token otherwise call signout ( as per below ).

using the Refresh Token

To refresh the token for a user's session, call the refreshToken() method. The value inside updateToken is in seconds. Sample code is shown in the box.

function refreshToken() {
        winkLoginClient
          .updateToken(0)
          .then(function (refreshed) {
            if (refreshed) {
              console.log('Token was successfully refreshed');
              winkLoadUserProfile();
            } else {
              console.log('Token is still valid');
            }
          })
          .catch(function (error) {
            console.log('Failed to refresh the token, or the session has expired');
            console.log(error);
          });
      }

Signing out a user

To sign-out the user, you can provide a sign-out option in your app, or you can manage the login session and automatically sign-out the user once the OAUTH2 tokens expire

To create a sign-out link, attach a function that calls the signOut() method to the link's onclick event.

function signOut() {
  winkLoginClient.winkLogout({
    onFailure: (error) => console.error(error),
  });
}

example code to extend session on activity and logout on idle

You can use the following code, refresh token code works when user is active for more than 5 mins since the time of login, the access token gets expired after completing 5 mins of login hence after this 5 mins this code will check if the user is performing some activity in the app, it will refresh the token else it will logout the user in case of inactivity.

var idleTime = 0;  
$(document).ready(function () {  
  var idleInterval = setInterval(timerIncrement, 60000); //60000: one minute in milliseconds  
  var events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'];  
  events.forEach(function (name) {  
    document.addEventListener(name, resetTimer, true);  
  });  
});  
function resetTimer() {  
  idleTime = 0;  
  var curtime = new Date().getTime();  
  var exptime = new Date(localStorage.getItem('tokenExpiry')).getTime()  
  if (winkLogin?.authenticated && (exptime - 60000) \< curtime) {  
    winkLogin.updateToken(0).then(function (refreshed) {  
      if (refreshed) {  
        //console.log(refreshed)  
      }  
    });  
  }  
}  
function timerIncrement() {  
  if (winkLogin?.authenticated) {  
    idleTime++;  
    if (idleTime >= 5) {  
      // Logout the user in case of inactivity  
      winkLogin.logout();  
      localStorage.removeItem('userInfo');  
    }  
  }  
}


What’s Next

Once you are done integrating the above in your application front end, you can handle the tokens in your Back-End code