> For the complete documentation index, see [llms.txt](https://docs.galaxyjoy.vn/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.galaxyjoy.vn/integration/html5-js.md).

# HTML5/JS

**Software Name:** Galaxy ID

**Software Version:** 0.1

### Acronyms and Terms

<table data-header-hidden><thead><tr><th width="150"></th><th width="150"></th><th></th></tr></thead><tbody><tr><td><strong>No.</strong></td><td><strong>Words</strong></td><td><strong>Descriptions</strong></td></tr><tr><td>1</td><td>GID</td><td>Galaxy ID</td></tr><tr><td>2</td><td>SSO</td><td>Single Sign-On</td></tr><tr><td>4</td><td>Client</td><td>An application that integrates for GID</td></tr></tbody></table>

### Summary

Galaxy ID is an SSO system. It provides endpoints that enable clients to authenticate and authorize in many places.

### Prepare

We will use a Javascript library, kecloak-js to integrate Galaxy ID. It can be installed via:

* NPM: <https://www.npmjs.com/package/keycloak-js>
* Yarn: <https://yarnpkg.com/package/keycloak-js>

Or you can also use keycloak.js directly.

### Integrate

#### Initialize **keycloak**

Place the keycloak.json file (supplied) in the same location as the HTML page and initialize:

```
<html>
<head>
    <script src="keycloak.js"></script>
    <script>
        function initKeycloak() {
            const keycloak = new Keycloak();
            keycloak.init().then(function(authenticated) {
                alert(authenticated ? 'authenticated' : 'not authenticated');
            }).catch(function() {
                alert('failed to initialize');
            });
        }
    </script>
</head>
<body onload="initKeycloak()">
    <!-- your page content goes here -->
</body>
</html>
```

Or you can also specify the keycloak.json file somewhere else:

```
 const keycloak = new Keycloak('http://localhost:8080/myapp/keycloak.json');
```

By default, for authentication, we need to call login. However, there are two options to automate the authentication work:

* *login-required:* It will authenticate if logged in or display the login page if not authenticated.
* *check-sso:* It will only authenticate if the user is logged in. If the user is not logged in, it will redirect back to the application.

To use, pass onLoad to the keycloak.init () function.&#x20;

```
keycloak.init({
    onLoad: 'check-sso'
})
```

We can also use check-sso silently without redirecting to the server and vice versa, but through a hidden iframe:

```
keycloak.init({
    onLoad: 'check-sso',
    silentCheckSsoRedirectUri: window.location.origin + '/silent-check-sso.html'
})
```

#### Token

After successful authentication, we can get Bearer token from keycloak.token

```
const loadData = function () {
    document.getElementById('username').innerText = keycloak.subject;

    const url = 'http://localhost:8080/restful-service';

    const req = new XMLHttpRequest();
    req.open('GET', url, true);
    req.setRequestHeader('Accept', 'application/json');
    req.setRequestHeader('Authorization', 'Bearer ' + keycloak.token);

    req.onreadystatechange = function () {
        if (req.readyState == 4) {
            if (req.status == 200) {
                alert('Success');
            } else if (req.status == 403) {
                alert('Forbidden');
            }
        }
    }

    req.send();
};
```

Since the lifetime of the access token is short, we need to update the new token by calling the updateToken method.

```
keycloak.updateToken(30).then(function() {
    loadData();
}).catch(function() {
    alert('Failed to refresh token');
});
```

#### Get user information

The user's information can be obtained from the returned token of the GID (recommended because it reduces the load of a significant request on the server) by calling keycloak.token parsed token parsed

![](/files/6B1iQCdWEsP0x7Z2NBNY)

Or it can also be done through the Restful API in the next section.

### APIs

#### Get user information

**URL**: \<host>/realms/\<realmName>/protocol/openid-connect/userinfo

**Method**: GET

**Header**: Authorization: Bearer \<access token> *(keycloak)*

Example request:

```
curl --location --request GET 'https://gid-stg.demoapp.info/realms/demo/protocol/openid-connect/userinfo' \
--header 'Authorization: Bearer <access token>'
```

Example response:

```
{
    "sub": "3d83889f-297f-4283-8602-73c6b60630be",
    "email_verified": false,
    "name": "Duy1 Doan",
    "preferred_username": "+84395883117",
    "given_name": "Duy1",
    "family_name": "Doan",
    "email": "duydoan1411@gmail.com"
}
```

#### Logout with API

**URL**: \<host>/realms/\<realmName>/protocol/openid-connect/logout

**Method**: GET

**Header**: Authorization: Bearer \<access token> *(keycloak)*

Example request:

```
curl --location --request POST 'https://gid-stg.demoapp.info/realms/gid-demo-testing/protocol/openid-connect/logout' \
--header 'Authorization: Bearer <access token>'
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id=gid-testing' \
--data-urlencode 'refresh_token=<refresh token>'
```

Example response:

* Status: 204 (No Content)

[keycloak-documentation/javascript-adapter.adoc at main · keycloak/keycloak-documentation (github.com)](https://github.com/keycloak/keycloak-documentation/blob/main/securing_apps/topics/oidc/javascript-adapter.adoc)
