To specify the location of the keycloak.json file:
[source]
----
var keycloak = Keycloak('http://localhost:8080/myapp/keycloak.json'));
----
Or finally to manually configure the adapter:
[source]
----
var keycloak = Keycloak({
url: 'http://keycloak-server/auth',
realm: 'myrealm',
clientId: 'myapp'
});
----
You can also pass `login-required` or `check-sso` to the init function.
Login required will cause a redirect to the login form on the server, while check-sso will simply redirect to the auth server to check if the user is already logged in to the realm.
For example:
[source]
----
keycloak.init({ onLoad: 'login-required' })
----
After you login, your application will be able to make REST calls using bearer token authentication.
Here's an example pulled from the `customer-portal-js` example that comes with the distribution.
The `loadData()` method builds an HTTP request setting the `Authorization` header to a bearer token.
The `keycloak.token` points to the access token the browser obtained when it logged you in.
The `loadFailure()` method is invoked on a failure.
The `reloadData()` function calls `keycloak.updateToken()` passing in the `loadData()` and `loadFailure()` callbacks.
The `keycloak.updateToken()` method checks to see if the access token hasn't expired.
If it hasn't, and your oauth login returned a refresh token, this method will refresh the access token.
Finally, if successful, it will invoke the success callback, which in this case is the `loadData()` method.
To refresh the token when it is expired, call the `updateToken` method.
This method returns a promise object, which can be used to invoke a function on success or failure.
This method can be used to wrap functions that should only be called with a valid token.
For example, the following method will refresh the token if it expires within 30 seconds, and then invoke the specified function.
If the token is valid for more than 30 seconds it will just call the specified function.
[source]
----
keycloak.updateToken(30).success(function() {
// send request with valid token
}).error(function() {
alert('failed to refresh token');
);
----
== Session status iframe
By default, the JavaScript adapter creates a non-visible iframe that is used to detect if a single-sign out has occurred.
This does not require any network traffic, instead the status is retrieved from a special status cookie.
This feature can be disabled by setting `checkLoginIframe: false` in the options passed to the `init` method.
[[_javascript_implicit_flow]]
== Implicit and Hybrid Flow
By default, the JavaScript adapter uses http://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth[OpenID Connect standard (Authorization code) flow], which means that after authentication, the Keycloak server redirects the user back to your application, where the JavaScript adapter will exchange the `code` for an access token and a refresh token.
However, Keycloak also supports http://openid.net/specs/openid-connect-core-1_0.html#ImplicitFlowAuth[OpenID Connect Implicit flow] where an access token is sent immediately after successful authentication with Keycloak (there is no additional request for exchange code). This could have better performance than standard flow, as there is no additional request to exchange the code for tokens.
However, sending the access token in the URL fragment could pose a security issue in some environments (access logs might expose tokens located in the URL).
To enable implicit flow, you need to enable the `Implicit Flow Enabled` flag for the client in the Keycloak admin console.
You also need to pass the parameter `flow` with value `implicit` to `init` method.
An example is below:
[source]
----
keycloak.init({ flow: 'implicit' })
----
Note that with implicit flow, you are not given a refresh token after authentication.
This makes it harder for your application to periodically update the access token in background (without browser redirection). It's recommended that you implement an `onTokenExpired` callback method on the keycloak object, so you are notified after the token is expired (For example you can call keycloak.login, which will redirect browser to Keycloak login screen and it will immediately redirect you back if the SSO session is still valid and the user is still logged.
However, make sure to save the application state before performing a redirect.)
Keycloak also has support for http://openid.net/specs/openid-connect-core-1_0.html#HybridFlowAuth[OpenID Connect Hybrid flow].
This requires the client to have both the `Standard Flow Enabled` and `Implicit Flow Enabled` flags enabled in the admin console.
The Keycloak server will then send both the code and tokens to your application.
The access token can be used immediately while the code can be exchanged for access and refresh tokens.
Similar to the implicit flow, the hybrid flow is good for performance because the access token is available immediately.
But, the token is still sent in the URL, and security risks might still apply.
However, one advantage over the implicit flow is that a refresh token is made available to the application (after the code-to-token request is finished).
For hybrid flow, you need to pass the parameter `flow` with value `hybrid` to `init` method.
== Older browsers
The JavaScript adapter depends on Base64 (window.btoa and window.atob) and HTML5 History API.
If you need to support browsers that don't provide those (for example IE9) you'll need to add polyfillers.
Example polyfill libraries:
* https://github.com/davidchambers/Base64.js
* https://github.com/devote/HTML5-History-API
== JavaScript Adapter reference
=== Constructor
[source]
----
new Keycloak();
new Keycloak('http://localhost/keycloak.json');
new Keycloak({ url: 'http://localhost/auth', realm: 'myrealm', clientId: 'myApp' });
----
=== Properties
* authenticated - true if the user is authenticated
* Authorization
* tokenParsed - the parsed token
* subject - the user id
* idToken - the id token if claims is enabled for the application, null otherwise
* idTokenParsed - the parsed id token
* realmAccess - the realm roles associated with the token
* resourceAccess - the resource roles assocaited with the token
* refreshToken - the base64 encoded token that can be used to retrieve a new token
* refreshTokenParsed - the parsed refresh token
* timeSkew - estimated skew between local time and Keycloak server in seconds
* fragment
* Implicit flow
* flow
=== Methods
==== init(options)
Called to initialize the adapter.
Options is an Object, where:
* onLoad - specifies an action to do on load, can be either 'login-required' or 'check-sso'
* token - set an initial value for the token
* refreshToken - set an initial value for the refresh token
* idToken - set an initial value for the id token (only together with token or refreshToken)
* timeSkew - set an initial value for skew between local time and Keycloak server in seconds (only together with token or refreshToken)
* checkLoginIframe - set to enable/disable monitoring login state (default is true)
* checkLoginIframeInterval - set the interval to check login state (default is 5 seconds)
* onReady(authenticated) - called when the adapter is initialized
* onAuthSuccess - called when a user is successfully authenticated
* onAuthError - called if there was an error during authentication
* onAuthRefreshSuccess - called when the token is refreshed
* onAuthRefreshError - called if there was an error while trying to refresh the token
* onAuthLogout - called if the user is logged out (will only be called if the session status iframe is enabled, or in Cordova mode)
* onTokenExpired - called when access token expired. When this happens you can for example refresh token, or if refresh not available (ie. with implicit flow) you can redirect to login screen