Skip to content

JavaScript OAuth2.0 client

We use the hello.js library to provide a gateway to Braincube OAuth2.0 server. So you have the possibility to use other providers via it like Google, Github, etc.

Our fork is available here. And you will find the script at this address.

Usage

You can use the following HTML example, taking care to insert your application id (#APP_ID) and the redirect url (#REDIRECT_URI)

Follow the instructions here to create an application in Braincube.

Once you have a valid OAuth2.0 token you need to open a SSO session to retrieve a SSO token and discuss with the Braincube API.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Braincube OAuth2.0 JavaScript example</title>
</head>
<body>

    <button id="login-button" onclick="login();">Login with Braincube</button>

    <div id="auth-container" style="display: none;">
        <h2>Authentication response</h2>
        <pre id="auth-response"></pre>
    </div>

    <div id="me-container" style="display: none;">
        <h2>Me</h2>
        <pre id="me-response"></pre>
    </div>

    <script src="https://cdn.mybraincube.com/oauth2.0/javascript.js"></script>
    <script>
        // Initialization with application options
        hello.init({
            braincube: '#APP_ID'
        }, {
            redirect_uri: '#REDIRECT_URI',
            scope: ['BASE', 'API']
        });

        var helloBraincube = hello('braincube');

        // This function is executed if authentication failed
        function authFailure(error) {
            alert('Error: ' + error.error.code);
        }

        // This function is executed if authentication succeeded
        function authSuccess(session) {
            document.querySelector('#login-button').style.display = 'none';

            document.querySelector('#auth-container').style.display = 'block';
            document.querySelector('#auth-response').innerText = JSON.stringify(session, null, 2);

            helloBraincube.api('me').then(function (result) {
                document.querySelector('#me-container').style.display = 'block';
                document.querySelector('#me-response').innerText = JSON.stringify(result, null, 2);
            });
        }

        // This function is executed when the connection button is clicked
        function login() {
            helloBraincube.login().then(authSuccess, authFailure);
        }

        // This function check if we have already a session
        function checkSession() {
            var currentTime = new Date().getTime() / 1000;

            var session = helloBraincube.getAuthResponse();

            if (session && session.access_token && session.expires > currentTime) {
                authSuccess(session);
            }
        }

        checkSession();
    </script>

</body>
</html>