Easy Keycloak setup for Angular applications.
This library helps you to use keycloak-js in Angular applications providing the following features:
keycloak-js
methods to be used in Angular, giving extrafunctionalities to the original functions and adding new methods to make it easier to be consumed byAngular applications.Run the following command to install both Keycloak Angular and the official Keycloak client library:
npm install keycloak-angular keycloak-js
Note that keycloak-js
is a peer dependency of Keycloak Angular. This change allows greater flexibility of choosing the right version of the Keycloak client version for your project.
Angular | keycloak-angular | keycloak-js | Support |
---|---|---|---|
11.x - 12.x | 8.4.x | 10 - 15 | Bugs / New Features |
10.x | 8.x.x | 10 - 11 | Bugs |
9.x | 7.3.x | 3.4.3 - 10 (excluding v7) | Bugs |
We try to support the same Angular versions that are supported by the Angular team. That said, it's always best to keep up to date with the latest version of Angular for optimal support.
The Keycloak client documentation recommends to use the same version of your Keycloak installation.
A best practice is to load the JavaScript adapter directly from Keycloak Server as it will automatically be updated when you upgrade the server. If you copy the adapter to your web application instead, make sure you upgrade the adapter only after you have upgraded the server.
In order to make sure Keycloak is initialized when your application is bootstrapped you will have to add an APP_INITIALIZER
provider to your AppModule
. This provider will call the initializeKeycloak
factory function shown below which will set up the Keycloak service so that it can be used in your application.
Use the code provided below as an example and implement it's functionality in your application. In this process ensure that the configuration you are providing matches that of your client as configured in Keycloak.
import { APP_INITIALIZER, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { KeycloakAngularModule, KeycloakService } from 'keycloak-angular';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
function initializeKeycloak(keycloak: KeycloakService) {
return () =>
keycloak.init({
config: {
url: 'http://localhost:8080/auth',
realm: 'your-realm',
clientId: 'your-client-id',
},
initOptions: {
onLoad: 'check-sso',
silentCheckSsoRedirectUri:
window.location.origin + '/assets/silent-check-sso.html',
},
});
}
@NgModule({
declarations: [AppComponent],
imports: [AppRoutingModule, BrowserModule, KeycloakAngularModule],
providers: [
{
provide: APP_INITIALIZER,
useFactory: initializeKeycloak,
multi: true,
deps: [KeycloakService],
},
],
bootstrap: [AppComponent],
})
export class AppModule {}
In the example we have set up Keycloak to use a silent check-sso
. With this feature enabled, your browser will not do a full redirect to the Keycloak server and back to your application, instead this action will be performed in a hidden iframe, so your application resources only need to be loaded and parsed once by the browser when the app is initialized and not again after the redirect back from Keycloak to your app.
To ensure that Keycloak can communicate through the iframe you will have to serve a static HTML asset from your application at the location provided in silentCheckSsoRedirectUri
.
Create a file called silent-check-sso.html
in the assets
directory of your application and paste in the contents as seen below.
<html>
<body>
<script>
parent.postMessage(location.href, location.origin);
</script>
</body>
</html>
If you want to know more about these options and various other capabilities of the Keycloak client is recommended to read the JavaScript Adapter documentation.
If you want to see an complete overview a pre-configured client together with a working Keycloak server make sure to check out the example project in this repository.
A generic AuthGuard, KeycloakAuthGuard
is provided to help you protect authenticated routes in your application. This guard provides you with information to see if the user is logged in and a list of roles from that belong to the user. In your implementation you just need to implement the desired logic to protect your routes.
To write your own implementation extend the KeycloakAuthGuard
class and implement the isAccessAllowed
method. For example the code provided below checks if the user is authenticated and if not the user is requested to sign in. It also checks if the user has the correct roles which could be provided by passing the roles
field into the data of the route.
import { Injectable } from '@angular/core';
import {
ActivatedRouteSnapshot,
Router,
RouterStateSnapshot,
} from '@angular/router';
import { KeycloakAuthGuard, KeycloakService } from 'keycloak-angular';
@Injectable({
providedIn: 'root',
})
export class AuthGuard extends KeycloakAuthGuard {
constructor(
protected readonly router: Router,
protected readonly keycloak: KeycloakService
) {
super(router, keycloak);
}
public async isAccessAllowed(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
) {
// Force the user to log in if currently unauthenticated.
if (!this.authenticated) {
await this.keycloak.login({
redirectUri: window.location.origin + state.url,
});
}
// Get the roles required from the route.
const requiredRoles = route.data.roles;
// Allow the user to to proceed if no additional roles are required to access the route.
if (!(requiredRoles instanceof Array) || requiredRoles.length === 0) {
return true;
}
// Allow the user to proceed if all the required roles are present.
return requiredRoles.every((role) => this.roles.includes(role));
}
}
By default all HttpClient requests will add the Authorization header in the format of: Authorization: Bearer TOKEN.
There is also the possibility to exclude a list of URLs that should not have the authorization header. The excluded list must be provided in the keycloak initialization. For example:
await keycloak.init({
config: {
url: 'http://localhost:8080/auth',
realm: 'your-realm',
clientId: 'your-client-id',
},
bearerExcludedUrls: ['/assets', '/clients/public'],
});
The callback events from keycloak-js are available through a RxJS subject which is defined by keycloakEvents$
.
For example you make keycloak-angular auto refreshing your access token when expired:
keycloakService.keycloakEvents$.subscribe({
next: e => {
if (e.type == KeycloakEventType.OnTokenExpired) {
keycloakService.updateToken(20);
}
}
});
Mauricio Gemelli Vigolo |
Jon Koops |
Frederik Prijck |
Jonathan Share |
jmparra |
Marcel Német |
Raphael Alex Silva Abreu |
---|
If you want to contribute to the project, please check out the contributingdocument.
keycloak-angular is licensed under the MIT license.
接上文《Keycloak通用接入手册(以Java为例)》,前面所述的,都是针对于服务器端的接入说明。 而现代化的前端技术,已经具备了很强大的native处理能力,很幸运,Keycloak已经提供JavaScript Adapter,它可以用于现代化的前端、移动端APP接入,GitHub上可以找到很多 VueJS、ReactJS、React Native的接入例子。
我使用Keycloak.js与Keycloak进行交互并获取低于错误的信息 Uncaught Error: [$injector:unpr] Unknown provider: AuthProvider module.factory('authInterceptor', ['$q', 'Auth', function($q, Auth) { return { request: function (
HTTP拦截是@ angular / common / http的一个主要特性 . 通过拦截,您可以声明拦截器,以检查和转换从您的应用程序到服务器的HTTP请求 . 相同的拦截器也可以在返回应用程序的路上检查和转换服务器的响应 . 多个拦截器形成一个前向链的请求/响应处理程序从'../auth.service'导入; @Injectable() 导出类AuthInterceptor实现HttpIn
Keycloak 是适用于现代应用程序和服务的开源身份和访问管理解决方案。以最少的麻烦为应用程序和安全服务添加身份验证,无需处理存储用户或对用户进行身份验证,开箱即用。包含用户联合,身份代理和社交登录等功能。
我在Wildfly10中部署ear时遇到了以下异常。安装了Apapter,因此ear中不包含JAR&不设置依赖项。 由:java.lang.noClassDefFounderror:org/keycloak/keycloakprincipal由:java.lang.classNotfoundexception:org.keycloak.keycloakprincipal由[Module\“depl
我正在评估一些IAM产品,遇到了一个使用KeyCloak的RealmResourceProvider的CORS问题。目标是编写一个angular4客户机,该客户机能够通过KeyCloak的REST接口创建用户和管理组。 服务器端: null 我的测试环境是来自hub.docker.com/r/jboss/keycloak/的offical docker容器
我正在尝试使用Keycloak REST API更改Keycloak用户登录ID。我的Keycloak版本是4.4.0,根据文档,在更新用户之前,我首先需要在RealmRepresentation中设置。我将此PUT API称为。 我可以知道做这件事的正确方法吗?
问题内容: 所以我有一个消耗api的客户端。该API使用密钥斗篷进行保护。用户可以正常登录,但是我想允许用户登录而不必使用他们的社交媒体帐户(例如facebook或google)进入keycloak的登录页面。我需要一个REST API,其中包含实现如何生成URL的实现,因此,当用户在按钮中单击此URL时,它将把用户带到相应的社交登录页面进行登录,而keycloak仍充当代理。 下面是我的实现,它
我想连接到我的组织的身份提供者,但它是失败的。为了测试键盘斗篷和其他身份提供者之间的连接,我使用了Github,并使用Github的默认键盘斗篷模板将其与键盘斗篷连接,它起作用了。 现在,我正在尝试使用通用的“OpenID connect v1.0”配置将Github与Keyclock连接起来,以检查它是否能对我有所帮助,但我没有成功。我被重定向到Github登录页面并登录,但当被重定向回Keyc