start UI implementing

This commit is contained in:
2026-08-18 21:38:57 +02:00
parent f040982b9c
commit d639cf3234
57692 changed files with 2619272 additions and 417 deletions
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+42
View File
@@ -0,0 +1,42 @@
# Keycloak JS
Keycloak is an Open Source Identity and Access Management solution for modern Applications and Services.
This repository contains the client-side JavaScript library that can be used to secure web applications and integrate them with Keycloak.
## Help and Documentation
* [Documentation](https://www.keycloak.org/documentation.html)
* [Keycloak JavaScript adapter guide](https://www.keycloak.org/securing-apps/javascript-adapter) - The specific guide for this client
* [User Mailing List](https://groups.google.com/g/keycloak-user) - Mailing list for help and general questions about Keycloak
## Reporting Security Vulnerabilities
If you've found a security vulnerability, please look at the [instructions on how to properly report it](http://www.keycloak.org/security.html)
## Reporting an issue
If you believe you have discovered a defect in the keycloak-js adapter please open an issue in our [Issue Tracker](https://github.com/keycloak/keycloak-js/issues).
Please remember to provide a good summary, description as well as steps to reproduce the issue.
The tracker can also be used for feature and enhancement requests.
## Getting started
To start with the keycloak-js adapter please try one of our [quickstarts](https://github.com/keycloak/keycloak-quickstarts).
For more details refer to the [Keycloak Documentation](https://www.keycloak.org/documentation.html).
## Contributing
Before contributing to keycloak-js adapter please read our [contributing guidelines](CONTRIBUTING.md).
## Other Keycloak Projects
* [Keycloak](https://github.com/keycloak/keycloak) - Keycloak Server and Java adapters
* [Keycloak QuickStarts](https://github.com/keycloak/keycloak-quickstarts) - QuickStarts for getting started with Keycloak
* [Keycloak Docker](https://github.com/keycloak/keycloak-containers) - Docker images for Keycloak
* [Keycloak Node.js Adapter](https://github.com/keycloak/keycloak-nodejs-connect) - Keycloak adapter for Node.js
## License
* [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0)
@@ -0,0 +1,143 @@
/*
* MIT License
*
* Copyright 2017 Brett Epps <https://github.com/eppsilon>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import Keycloak from './keycloak.js'
export interface KeycloakAuthorizationPromise {
then: (onGrant: (rpt: string) => void, onDeny: () => void, onError: () => void) => void
}
export interface AuthorizationRequest {
/**
* An array of objects representing the resource and scopes.
*/
permissions?: ResourcePermission[]
/**
* A permission ticket obtained from a resource server when using UMA authorization protocol.
*/
ticket?: string
/**
* A boolean value indicating whether the server should create permission requests to the resources
* and scopes referenced by a permission ticket. This parameter will only take effect when used together
* with the ticket parameter as part of a UMA authorization process.
*/
submitRequest?: boolean
/**
* Defines additional information about this authorization request in order to specify how it should be processed
* by the server.
*/
metadata?: AuthorizationRequestMetadata
/**
* Defines whether or not this authorization request should include the current RPT. If set to true, the RPT will
* be sent and permissions in the current RPT will be included in the new RPT. Otherwise, only the permissions referenced in this
* authorization request will be granted in the new RPT.
*/
incrementalAuthorization?: boolean
}
export interface AuthorizationRequestMetadata {
/**
* A boolean value indicating to the server if resource names should be included in the RPT’s permissions.
* If false, only the resource identifier is included.
*/
responseIncludeResourceName?: any
/**
* An integer N that defines a limit for the amount of permissions an RPT can have. When used together with
* rpt parameter, only the last N requested permissions will be kept in the RPT.
*/
response_permissions_limit?: number
}
export interface ResourcePermission {
/**
* The id or name of a resource.
*/
id: string
/**
* An array of strings where each value is the name of a scope associated with the resource.
*/
scopes?: string[]
}
/**
* @deprecated Instead of importing 'KeycloakAuthorizationInstance' you can import 'KeycloakAuthorization' directly as a type.
*/
export type KeycloakAuthorizationInstance = KeycloakAuthorization
/**
* @deprecated Construct a KeycloakAuthorization instance using the `new` keyword instead.
*/
declare function KeycloakAuthorization (keycloak: Keycloak): KeycloakAuthorization
declare class KeycloakAuthorization {
/**
* Creates a new Keycloak client instance.
* @param config Path to a JSON config file or a plain config object.
*/
constructor (keycloak: Keycloak)
rpt: any
config: { rpt_endpoint: string }
/**
* Initializes the `KeycloakAuthorization` instance.
* @deprecated Initialization now happens automatically, calling this method is no longer required.
*/
init (): void
/**
* A promise that resolves when the `KeycloakAuthorization` instance is initialized.
* @deprecated Initialization now happens automatically, using this property is no longer required.
*/
ready: Promise<void>
/**
* This method enables client applications to better integrate with resource servers protected by a Keycloak
* policy enforcer using UMA protocol.
*
* The authorization request must be provided with a ticket.
*
* @param authorizationRequest An AuthorizationRequest instance with a valid permission ticket set.
* @returns A promise to set functions to be invoked on grant, deny or error.
*/
authorize (authorizationRequest: AuthorizationRequest): KeycloakAuthorizationPromise
/**
* Obtains all entitlements from a Keycloak server based on a given resourceServerId.
*
* @param resourceServerId The id (client id) of the resource server to obtain permissions from.
* @param authorizationRequest An AuthorizationRequest instance.
* @returns A promise to set functions to be invoked on grant, deny or error.
*/
entitlement (resourceServerId: string, authorizationRequest?: AuthorizationRequest): KeycloakAuthorizationPromise
}
export default KeycloakAuthorization
/**
* @deprecated The 'KeycloakAuthorization' namespace is deprecated, use named imports instead.
*/
export as namespace KeycloakAuthorization;
@@ -0,0 +1,296 @@
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
const KeycloakAuthorization = function (keycloak, options) {
const _instance = this
this.rpt = null
// Only here for backwards compatibility, as the configuration is now loaded on demand.
// See:
// - https://github.com/keycloak/keycloak/pull/6619
// - https://issues.redhat.com/browse/KEYCLOAK-10894
// TODO: Remove both `ready` property and `init` method in a future version
Object.defineProperty(this, 'ready', {
get () {
console.warn("The 'ready' property is deprecated and will be removed in a future version. Initialization now happens automatically, using this property is no longer required.")
return Promise.resolve()
}
})
this.init = () => {
console.warn("The 'init()' method is deprecated and will be removed in a future version. Initialization now happens automatically, calling this method is no longer required.")
}
/** @type {Promise<unknown> | undefined} */
let configPromise
/**
* Initializes the configuration or re-uses the existing one if present.
* @returns {Promise<void>} A promise that resolves when the configuration is loaded.
*/
async function initializeConfigIfNeeded () {
if (_instance.config) {
return _instance.config
}
if (configPromise) {
return await configPromise
}
if (!keycloak.didInitialize) {
throw new Error('The Keycloak instance has not been initialized yet.')
}
configPromise = loadConfig(keycloak.authServerUrl, keycloak.realm)
_instance.config = await configPromise
}
/**
* This method enables client applications to better integrate with resource servers protected by a Keycloak
* policy enforcer using UMA protocol.
*
* The authorization request must be provided with a ticket.
*/
this.authorize = function (authorizationRequest) {
this.then = async function (onGrant, onDeny, onError) {
try {
await initializeConfigIfNeeded()
} catch (error) {
handleError(error, onError)
return
}
if (authorizationRequest && authorizationRequest.ticket) {
const request = new globalThis.XMLHttpRequest()
request.open('POST', _instance.config.token_endpoint, true)
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
request.setRequestHeader('Authorization', 'Bearer ' + keycloak.token)
request.onreadystatechange = function () {
if (request.readyState === 4) {
const status = request.status
if (status >= 200 && status < 300) {
const rpt = JSON.parse(request.responseText).access_token
_instance.rpt = rpt
onGrant(rpt)
} else if (status === 403) {
if (onDeny) {
onDeny()
} else {
console.error('Authorization request was denied by the server.')
}
} else {
if (onError) {
onError()
} else {
console.error('Could not obtain authorization data from server.')
}
}
}
}
let params = 'grant_type=urn:ietf:params:oauth:grant-type:uma-ticket&client_id=' + keycloak.clientId + '&ticket=' + authorizationRequest.ticket
if (authorizationRequest.submitRequest !== undefined) {
params += '&submit_request=' + authorizationRequest.submitRequest
}
const metadata = authorizationRequest.metadata
if (metadata) {
if (metadata.responseIncludeResourceName) {
params += '&response_include_resource_name=' + metadata.responseIncludeResourceName
}
if (metadata.responsePermissionsLimit) {
params += '&response_permissions_limit=' + metadata.responsePermissionsLimit
}
}
if (_instance.rpt && (authorizationRequest.incrementalAuthorization === undefined || authorizationRequest.incrementalAuthorization)) {
params += '&rpt=' + _instance.rpt
}
request.send(params)
}
}
return this
}
/**
* Obtains all entitlements from a Keycloak Server based on a given resourceServerId.
*/
this.entitlement = function (resourceServerId, authorizationRequest) {
this.then = async function (onGrant, onDeny, onError) {
try {
await initializeConfigIfNeeded()
} catch (error) {
handleError(error, onError)
return
}
const request = new globalThis.XMLHttpRequest()
request.open('POST', _instance.config.token_endpoint, true)
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
request.setRequestHeader('Authorization', 'Bearer ' + keycloak.token)
request.onreadystatechange = function () {
if (request.readyState === 4) {
const status = request.status
if (status >= 200 && status < 300) {
const rpt = JSON.parse(request.responseText).access_token
_instance.rpt = rpt
onGrant(rpt)
} else if (status === 403) {
if (onDeny) {
onDeny()
} else {
console.error('Authorization request was denied by the server.')
}
} else {
if (onError) {
onError()
} else {
console.error('Could not obtain authorization data from server.')
}
}
}
}
if (!authorizationRequest) {
authorizationRequest = {}
}
let params = 'grant_type=urn:ietf:params:oauth:grant-type:uma-ticket&client_id=' + keycloak.clientId
if (authorizationRequest.claimToken) {
params += '&claim_token=' + authorizationRequest.claimToken
if (authorizationRequest.claimTokenFormat) {
params += '&claim_token_format=' + authorizationRequest.claimTokenFormat
}
}
params += '&audience=' + resourceServerId
let permissions = authorizationRequest.permissions
if (!permissions) {
permissions = []
}
for (let i = 0; i < permissions.length; i++) {
const resource = permissions[i]
let permission = resource.id
if (resource.scopes && resource.scopes.length > 0) {
permission += '#'
for (let j = 0; j < resource.scopes.length; j++) {
const scope = resource.scopes[j]
if (permission.indexOf('#') !== permission.length - 1) {
permission += ','
}
permission += scope
}
}
params += '&permission=' + permission
}
const metadata = authorizationRequest.metadata
if (metadata) {
if (metadata.responseIncludeResourceName) {
params += '&response_include_resource_name=' + metadata.responseIncludeResourceName
}
if (metadata.responsePermissionsLimit) {
params += '&response_permissions_limit=' + metadata.responsePermissionsLimit
}
}
if (_instance.rpt) {
params += '&rpt=' + _instance.rpt
}
request.send(params)
}
return this
}
return this
}
/**
* Obtains the configuration from the server.
* @param {string} serverUrl The URL of the Keycloak server.
* @param {string} realm The realm name.
* @returns {Promise<unknown>} A promise that resolves when the configuration is loaded.
*/
async function loadConfig (serverUrl, realm) {
const url = `${serverUrl}/realms/${encodeURIComponent(realm)}/.well-known/uma2-configuration`
try {
return await fetchJSON(url)
} catch (error) {
throw new Error('Could not obtain configuration from server.', { cause: error })
}
}
/**
* Fetches the JSON data from the given URL.
* @param {string} url The URL to fetch the data from.
* @returns {Promise<unknown>} A promise that resolves when the data is loaded.
*/
async function fetchJSON (url) {
let response
try {
response = await fetch(url)
} catch (error) {
throw new Error('Server did not respond.', { cause: error })
}
if (!response.ok) {
throw new Error('Server responded with an invalid status.')
}
try {
return await response.json()
} catch (error) {
throw new Error('Server responded with invalid JSON.', { cause: error })
}
}
/**
* @param {unknown} error
* @param {((error: unknown) => void) | undefined} handler
*/
function handleError (error, handler) {
if (handler) {
handler(error)
} else {
console.error(error)
}
}
export default KeycloakAuthorization
@@ -0,0 +1,692 @@
/*
* MIT License
*
* Copyright 2017 Brett Epps <https://github.com/eppsilon>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
export type KeycloakOnLoad = 'login-required' | 'check-sso'
export type KeycloakResponseMode = 'query' | 'fragment'
export type KeycloakResponseType = 'code' | 'id_token token' | 'code id_token token'
export type KeycloakFlow = 'standard' | 'implicit' | 'hybrid'
export type KeycloakPkceMethod = 'S256' | false
export interface KeycloakServerConfig {
/**
* URL to the Keycloak server, for example: http://keycloak-server/auth
*/
url: string
/**
* Name of the realm, for example: 'myrealm'
*/
realm: string
/**
* Client identifier, example: 'myapp'
*/
clientId: string
}
export interface GenericOidcConfig {
/**
* Client identifier, example: 'myapp'
*/
clientId: string
/** Generic OpenID Connect configuration, can be a URL to the discovery metadata endpoint, or the metadata itself. */
oidcProvider: string | OpenIdProviderMetadata
}
/**
* OpenIdProviderMetadata The OpenID version of the adapter configuration, based on the {@link https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata OpenID Connect Discovery specification}.
*/
export interface OpenIdProviderMetadata {
/** URL of the OP's OAuth 2.0 Authorization Endpoint. */
authorization_endpoint: string
/** URL of the OP's OAuth 2.0 Token Endpoint. */
token_endpoint: string
/** URL of the OP's UserInfo Endpoint. */
userinfo_endpoint?: string
/** URL of an OP iframe that supports cross-origin communications for session state information with the RP Client, using the HTML5 postMessage API. */
check_session_iframe?: string
/** URL at the OP to which an RP can perform a redirect to request that the End-User be logged out at the OP. */
end_session_endpoint?: string
}
export type KeycloakConfig = KeycloakServerConfig | GenericOidcConfig
export interface Acr {
/**
* Array of values, which will be used inside ID Token `acr` claim sent inside the `claims` parameter to Keycloak server during login.
* Values should correspond to the ACR levels defined in the ACR to Loa mapping for realm or client or to the numbers (levels) inside defined
* Keycloak authentication flow. See section 5.5.1 of OIDC 1.0 specification for the details.
*/
values: string[]
/**
* This parameter specifies if ACR claims is considered essential or not.
*/
essential: boolean
}
export interface KeycloakInitOptions {
/**
* Adds a [cryptographic nonce](https://en.wikipedia.org/wiki/Cryptographic_nonce)
* to verify that the authentication response matches the request.
* @default true
*/
useNonce?: boolean
/**
*
* Allow usage of different types of adapters or a custom adapter to make Keycloak work in different environments.
*
* The following options are supported:
* - `default` - Use default APIs that are available in browsers.
* - `cordova` - Use a WebView in Cordova.
* - `cordova-native` - Use Cordova native APIs, this is recommended over `cordova`.
*
* It's also possible to pass in a custom adapter for the environment you are running Keycloak in. In order to do so extend the `KeycloakAdapter` interface and implement the methods that are defined there.
*
* For example:
*
* ```ts
* // Implement the 'KeycloakAdapter' interface so that all required methods are guaranteed to be present.
* const MyCustomAdapter: KeycloakAdapter = {
* login(options) {
* // Write your own implementation here.
* }
*
* // The other methods go here...
* };
*
* keycloak.init({
* adapter: MyCustomAdapter,
* });
* ```
*/
adapter?: 'default' | 'cordova' | 'cordova-native' | KeycloakAdapter
/**
* Specifies an action to do on load.
*/
onLoad?: KeycloakOnLoad
/**
* Set an initial value for the token.
*/
token?: string
/**
* Set an initial value for the refresh token.
*/
refreshToken?: string
/**
* Set an initial value for the id token (only together with `token` or
* `refreshToken`).
*/
idToken?: string
/**
* Set an initial value for skew between local time and Keycloak server in
* seconds (only together with `token` or `refreshToken`).
*/
timeSkew?: number
/**
* Set to enable/disable monitoring login state.
* @default true
*/
checkLoginIframe?: boolean
/**
* Set the interval to check login state (in seconds).
* @default 5
*/
checkLoginIframeInterval?: number
/**
* Set the OpenID Connect response mode to send to Keycloak upon login.
* @default fragment After successful authentication Keycloak will redirect
* to JavaScript application with OpenID Connect parameters
* added in URL fragment. This is generally safer and
* recommended over query.
*/
responseMode?: KeycloakResponseMode
/**
* Specifies a default uri to redirect to after login or logout.
* This is currently supported for adapter 'cordova-native' and 'default'
*/
redirectUri?: string
/**
* Specifies an uri to redirect to after silent check-sso.
* Silent check-sso will only happen, when this redirect uri is given and
* the specified uri is available within the application.
*/
silentCheckSsoRedirectUri?: string
/**
* Specifies whether the silent check-sso should fallback to "non-silent"
* check-sso when 3rd party cookies are blocked by the browser. Defaults
* to true.
*/
silentCheckSsoFallback?: boolean
/**
* Set the OpenID Connect flow.
* @default standard
*/
flow?: KeycloakFlow
/**
* Configures the Proof Key for Code Exchange (PKCE) method to use. This will default to 'S256'.
* Can be disabled by passing `false`.
*/
pkceMethod?: KeycloakPkceMethod
/**
* Enables logging messages from Keycloak to the console.
* @default false
*/
enableLogging?: boolean
/**
* Set the default scope parameter to the login endpoint. Use a space-delimited list of scopes.
* Note that the scope 'openid' will be always be added to the list of scopes by the adapter.
* Note that the default scope specified here is overwritten if the `login()` options specify scope explicitly.
*/
scope?: string
/**
* Configures how long will Keycloak adapter wait for receiving messages from server in ms. This is used,
* for example, when waiting for response of 3rd party cookies check.
*
* @default 10000
*/
messageReceiveTimeout?: number
/**
* When onLoad is 'login-required', sets the 'ui_locales' query param in compliance with section 3.1.2.1
* of the OIDC 1.0 specification.
*/
locale?: string
/**
* HTTP method for calling the end_session endpoint. Defaults to 'GET'.
*/
logoutMethod?: 'GET' | 'POST'
}
export interface KeycloakLoginOptions {
/**
* Specifies the scope parameter for the login url
* The scope 'openid' will be added to the scope if it is missing or undefined.
*/
scope?: string
/**
* Specifies the uri to redirect to after login.
*/
redirectUri?: string
/**
* By default the login screen is displayed if the user is not logged into
* Keycloak. To only authenticate to the application if the user is already
* logged in and not display the login page if the user is not logged in, set
* this option to `'none'`. To always require re-authentication and ignore
* SSO, set this option to `'login'`. To always prompt the user for consent,
* set this option to `'consent'`. This ensures that consent is requested,
* even if it has been given previously.
*/
prompt?: 'none' | 'login' | 'consent'
/**
* If value is `'register'` then user is redirected to registration page,
* otherwise to login page.
*/
action?: string
/**
* Used just if user is already authenticated. Specifies maximum time since
* the authentication of user happened. If user is already authenticated for
* longer time than `'maxAge'`, the SSO is ignored and he will need to
* authenticate again.
*/
maxAge?: number
/**
* Used to pre-fill the username/email field on the login form.
*/
loginHint?: string
/**
* Sets the `acr` claim of the ID token sent inside the `claims` parameter. See section 5.5.1 of the OIDC 1.0 specification.
*/
acr?: Acr
/**
* Configures the 'acr_values' query param in compliance with section 3.1.2.1
* of the OIDC 1.0 specification.
* Used to tell Keycloak what level of authentication the user needs.
*/
acrValues?: string
/**
* Used to tell Keycloak which IDP the user wants to authenticate with.
*/
idpHint?: string
/**
* Sets the 'ui_locales' query param in compliance with section 3.1.2.1
* of the OIDC 1.0 specification.
*/
locale?: string
/**
* Specifies arguments that are passed to the Cordova in-app-browser (if applicable).
* Options 'hidden' and 'location' are not affected by these arguments.
* All available options are defined at https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-inappbrowser/.
* Example of use: { zoom: "no", hardwareback: "yes" }
*/
cordovaOptions?: { [optionName: string]: string }
}
export interface KeycloakLogoutOptions {
/**
* Specifies the uri to redirect to after logout.
*/
redirectUri?: string
/**
* HTTP method for calling the end_session endpoint. Defaults to 'GET'.
*/
logoutMethod?: 'GET' | 'POST'
}
export interface KeycloakRegisterOptions extends Omit<KeycloakLoginOptions, 'action'> { }
export interface KeycloakAccountOptions {
/**
* Specifies the uri to redirect to when redirecting back to the application.
*/
redirectUri?: string
}
export interface KeycloakError {
error: string
error_description: string
}
export interface KeycloakRedirectUriOptions {
/**
* Specifies the uri to redirect to after login.
*/
redirectUri?: string
}
export interface KeycloakAdapter {
login: (options?: KeycloakLoginOptions) => Promise<void>
logout: (options?: KeycloakLogoutOptions) => Promise<void>
register: (options?: KeycloakRegisterOptions) => Promise<void>
accountManagement: () => Promise<void>
redirectUri: (options?: KeycloakRedirectUriOptions) => string
}
export interface KeycloakProfile {
id?: string
username?: string
email?: string
firstName?: string
lastName?: string
enabled?: boolean
emailVerified?: boolean
totp?: boolean
createdTimestamp?: number
attributes?: Record<string, unknown>
}
export interface KeycloakTokenParsed {
iss?: string
sub?: string
aud?: string
exp?: number
iat?: number
auth_time?: number
nonce?: string
acr?: string
amr?: string
azp?: string
session_state?: string
realm_access?: KeycloakRoles
resource_access?: KeycloakResourceAccess
[key: string]: any // Add other attributes here.
}
export interface KeycloakResourceAccess {
[key: string]: KeycloakRoles
}
export interface KeycloakRoles {
roles: string[]
}
export interface KeycloakUserInfo {
sub: string
[key: string]: any
}
/**
* @deprecated Instead of importing 'KeycloakInstance' you can import 'Keycloak' directly as a type.
*/
export type KeycloakInstance = Keycloak
/**
* A client for the Keycloak authentication server.
* @see {@link https://keycloak.gitbooks.io/securing-client-applications-guide/content/topics/oidc/javascript-adapter.html|Keycloak JS adapter documentation}
*/
declare class Keycloak {
/**
* Creates a new Keycloak client instance.
* @param config A configuration object or path to a JSON config file.
*/
constructor (config: KeycloakConfig | string)
/**
* Is true if the user is authenticated, false otherwise.
*/
authenticated: boolean
/**
* The user id.
*/
subject?: string
/**
* Response mode passed in init (default value is `'fragment'`).
*/
responseMode: KeycloakResponseMode
/**
* Response type sent to Keycloak with login requests. This is determined
* based on the flow value used during initialization, but can be overridden
* by setting this value.
*/
responseType: KeycloakResponseType
/**
* Flow passed in init.
*/
flow: KeycloakFlow
/**
* The realm roles associated with the token.
*/
realmAccess?: KeycloakRoles
/**
* The resource roles associated with the token.
*/
resourceAccess?: KeycloakResourceAccess
/**
* The base64 encoded token that can be sent in the Authorization header in
* requests to services.
*/
token?: string
/**
* The parsed token as a JavaScript object.
*/
tokenParsed?: KeycloakTokenParsed
/**
* The base64 encoded refresh token that can be used to retrieve a new token.
*/
refreshToken?: string
/**
* The parsed refresh token as a JavaScript object.
*/
refreshTokenParsed?: KeycloakTokenParsed
/**
* The base64 encoded ID token.
*/
idToken?: string
/**
* The parsed id token as a JavaScript object.
*/
idTokenParsed?: KeycloakTokenParsed
/**
* The estimated time difference between the browser time and the Keycloak
* server in seconds. This value is just an estimation, but is accurate
* enough when determining if a token is expired or not.
*/
timeSkew: number | null
/**
* Whether the instance has been initialized by calling `.init()`.
*/
didInitialize: boolean
/**
* @private Undocumented.
*/
loginRequired: boolean
/**
* @private Undocumented.
*/
authServerUrl?: string
/**
* @private Undocumented.
*/
realm?: string
/**
* @private Undocumented.
*/
clientId?: string
/**
* @private Undocumented.
*/
redirectUri?: string
/**
* @private Undocumented.
*/
sessionId?: string
/**
* @private Undocumented.
*/
profile?: KeycloakProfile
/**
* @private Undocumented.
*/
userInfo?: KeycloakUserInfo
/**
* Called when the adapter is initialized.
*/
onReady? (authenticated?: boolean): void
/**
* Called when a user is successfully authenticated.
*/
onAuthSuccess? (): void
/**
* Called if there was an error during authentication.
*/
onAuthError? (errorData?: KeycloakError): void
/**
* Called when the token is refreshed.
*/
onAuthRefreshSuccess? (): void
/**
* Called if there was an error while trying to refresh the token.
*/
onAuthRefreshError? (): void
/**
* Called if the user is logged out (will only be called if the session
* status iframe is enabled, or in Cordova mode).
*/
onAuthLogout? (): void
/**
* Called when the access token is expired. If a refresh token is available
* the token can be refreshed with Keycloak#updateToken, or in cases where
* it's not (ie. with implicit flow) you can redirect to login screen to
* obtain a new access token.
*/
onTokenExpired? (): void
/**
* Called when a AIA has been requested by the application.
* @param status the outcome of the required action
* @param action the alias name of the required action, e.g. UPDATE_PASSWORD, CONFIGURE_TOTP etc.
*/
onActionUpdate? (status: 'success' | 'cancelled' | 'error', action?: string): void
/**
* Called to initialize the adapter.
* @param initOptions Initialization options.
* @returns A promise to set functions to be invoked on success or error.
*/
init (initOptions?: KeycloakInitOptions): Promise<boolean>
/**
* Redirects to login form.
* @param options Login options.
*/
login (options?: KeycloakLoginOptions): Promise<void>
/**
* Redirects to logout.
* @param options Logout options.
*/
logout (options?: KeycloakLogoutOptions): Promise<void>
/**
* Redirects to registration form.
* @param options The options used for the registration.
*/
register (options?: KeycloakRegisterOptions): Promise<void>
/**
* Redirects to the Account Management Console.
*/
accountManagement (): Promise<void>
/**
* Returns the URL to login form.
* @param options Supports same options as Keycloak#login.
*/
createLoginUrl (options?: KeycloakLoginOptions): Promise<string>
/**
* Returns the URL to logout the user.
* @param options Logout options.
*/
createLogoutUrl (options?: KeycloakLogoutOptions): string
/**
* Returns the URL to registration page.
* @param options The options used for creating the registration URL.
*/
createRegisterUrl (options?: KeycloakRegisterOptions): Promise<string>
/**
* Returns the URL to the Account Management Console.
* @param options The options used for creating the account URL.
*/
createAccountUrl (options?: KeycloakAccountOptions): string
/**
* Returns true if the token has less than `minValidity` seconds left before
* it expires.
* @param minValidity If not specified, `0` is used.
*/
isTokenExpired (minValidity?: number): boolean
/**
* If the token expires within `minValidity` seconds, the token is refreshed.
* If the session status iframe is enabled, the session status is also
* checked.
* @param minValidity If not specified, `5` is used.
* @returns A promise to set functions that can be invoked if the token is
* still valid, or if the token is no longer valid.
* @example
* ```js
* keycloak.updateToken(5).then(function(refreshed) {
* if (refreshed) {
* alert('Token was successfully refreshed');
* } else {
* alert('Token is still valid');
* }
* }).catch(function() {
* alert('Failed to refresh the token, or the session has expired');
* });
*/
updateToken (minValidity?: number): Promise<boolean>
/**
* Clears authentication state, including tokens. This can be useful if
* the application has detected the session was expired, for example if
* updating token fails. Invoking this results in Keycloak#onAuthLogout
* callback listener being invoked.
*/
clearToken (): void
/**
* Returns true if the token has the given realm role.
* @param role A realm role name.
*/
hasRealmRole (role: string): boolean
/**
* Returns true if the token has the given role for the resource.
* @param role A role name.
* @param resource If not specified, `clientId` is used.
*/
hasResourceRole (role: string, resource?: string): boolean
/**
* Loads the user's profile.
* @returns A promise to set functions to be invoked on success or error.
*/
loadUserProfile (): Promise<KeycloakProfile>
/**
* @private Undocumented.
*/
loadUserInfo (): Promise<KeycloakUserInfo>
}
export default Keycloak
/**
* @deprecated The 'Keycloak' namespace is deprecated, use named imports instead.
*/
export as namespace Keycloak;
File diff suppressed because it is too large Load Diff
+47
View File
@@ -0,0 +1,47 @@
{
"name": "keycloak-js",
"version": "26.2.4",
"type": "module",
"description": "A client-side JavaScript OpenID Connect library that can be used to secure web applications.",
"scripts": {
"lint": "ts-standard",
"guides": "node docs/guides/guides.mjs $npm_package_version"
},
"workspaces": [
"test"
],
"exports": {
".": {
"types": "./lib/keycloak.d.ts",
"default": "./lib/keycloak.js"
},
"./authz": {
"types": "./lib/keycloak-authz.d.ts",
"default": "./lib/keycloak-authz.js"
}
},
"files": [
"lib"
],
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/keycloak/keycloak-js.git"
},
"author": "Keycloak",
"license": "Apache-2.0",
"homepage": "https://www.keycloak.org",
"keywords": [
"keycloak",
"sso",
"oauth",
"oauth2",
"authentication"
],
"devDependencies": {
"jszip": "^3.10.1",
"ts-standard": "^12.0.2"
}
}