本文介绍了Keycloak基础知识、ADFS和Salesforce IDP配置、Spring Boot和Angular集成Keycloak实现单点登陆的方法。javascript
本文代码以Angular 8集成Spring Boot 2详解为基础,删除了原JWT、用户、权限、登陆等代码。Angular代码使用了keycloak-angular,稍作修改。GitHub源码地址:heroes-api 、heroes-web 。html
软件环境:
Keycloak 7.0.1
Spring Boot 2.2.0
Angular 8.2
ADFS 2016
Salesforce Cloudjava
Keycloak为现代应用和服务提供开源的认证和访问管理,即一般所说的认证和受权。Keycloak支持OpenID、OAuth 2.0和SAML 2.0协议;支持用户注册、用户管理、权限管理;支持OTP,支持代理OpenID、SAML 2.0 IDP,支持GitHub、LinkedIn等第三方登陆,支持整合LDAP和Active Directory;支持自定义认证流程、自定义用户界面,支持国际化。git
Keycloak支持Java、C#、Python、Android、iOS、JavaScript、Nodejs等平台或语言,提供简单易用的Adapter,仅需少许配置和代码便可实现SSO。github
Keycloak新的发行版命名为Quarkus,专为GraalVM和OpenJDK HotSpot量身定制的一个Kurbernetes Native Java框架,计划2019年末正式发布。web
Keycloak构建在WildFly application server之上,从官网下载Standalone server distribution解压后运行bin/standalone.sh便可启动。默认使用h2数据库,能够修改配置使用其它数据库。Standalone Clustered Mode、Domain Clustered Mode启动模式和更多配置请参阅官方文档。
默认,本地网址为http://localhost:8080/auth ,首次登陆时必须建立admin用户:
直接登陆Admin Console http://localhost:8080/auth/admin/ :算法
为保护不一样的应用,一般建立不一样的Realm,各Realm间的数据和配置是独立的。初始建立的Realm为Master,Master是最高级别的Realm。Master Realm内的admin用户(授予admin角色的用户)拥有查看和管理任何其它realm的权限。所以,不推荐使用master realm管理用户和应用,而应仅供超级管理员来建立和管理realm。
每一个realm有专用的管理控制台,能够设置自已的管理员帐号,好比接下来咱们建立的heroes realm,控制台网址为http://localhost:8080/auth/admin/heroes/console 。
建立Heroes realm
点击左上角下拉菜单 -> Add realm:
Login Tab中有多个可配置选项:用户注册、编辑用户名、忘记密码、记住我、验证email、使用email登陆、须要SSL。
其中,Require SSL有三个选项:all requests、external requests、none,默认为external requests,在生产环境中应配置为all requests。spring
Themes Tab能够配置界面主题、启用国际化:
Tokens Tab能够配置token签名算法、过时时间等。数据库
Client是realm中受信任的应用。
建立realm后自动建立如下client:json
如Realm配置中启用了User-Managed Access则能够管理本身的Resource:
建立heroes client
点击Clients右上方的Create:
Client Protocol使用默认值openid-connect。Access Type有三个选项confidential、public、bearer-only,保持默认值public。confidential须要client secret,但咱们将在web应用中使用此client,web没法以安全的方式传输secret,所以必须使用public client。只要严格使用HTTPS,能够保证安全。Valid Redirect URIs输入 http://localhost:4200/* 。
认证流程:
调用示例,POST请求地址:http://localhost:8080/auth/realms/heroes/protocol/openid-connect/token :
OIDC URI Endpoints
查询网址:http://localhost:8080/auth/realms/heroes/.well-known/openid-configuration ,这些Endpoint是很是有用的,好比REST调用。
Client Scope定义了协议映射关系,keycloak预约义了一些Scope,每一个client会自动继承,这样就没必要在client内重复定义mapper了。Client Scope分为default和optional两种, default scope会自动生效,optional scope指定使用时才生效。
启用optional scope须要使用scope参数:
启用相应scope或配置mapper后,才能在token或userinfo中显示相应的属性。好比,上图中咱们启用了phone scope,其mapper中定义了phone number:
若是用户属性中定义了phoneNumber,在token中则会显示phone_number,能够在heroes client -> Client Scopes -> Evaluate查看效果:
Role
Role分为两种级别:Realm、Client,默认Realm Role:offline_access、uma_authorization。
Role、Group和User的关系
User能够属于一个或多个Group,Role能够授予User和Group。
建立Realm管理用户
添加用户:
授予realm-management权限:
Keycloak预约义了Browser、Direct Grant、Registration、Reset Credentials等认证流程,用户也可自定义流程。以Brower流程为例:
Required是必须执行的,Alternative至少须执行一个,Optional则由用户决定是否启用。Browser流程中Cookie(Session Cookie)、Identity Provider Redirector、Forms均为Alternative,所以只有前者没有验证成功才会执行后者。其中Identity Provider能够配置默认IDP;当执行Form认证时,用户名/密码是必须的,OTP为可选的。
用户启用OTP的方法,登陆Account Console,点击认证方,根听说明操做便可:
支持代理OpenID、SAML 2.0 IDP,支持社交登陆。不管您采用什么认证方式,token都由keycloak签发,彻底与外部IDP解耦,客户端不需知道keycloak与IDP使用的协议,简化了认证和受权管理。
Identity Broker Flow:
解释一下第七、8步:
IDP认证成功后,重定向到keycloak,一般返回的响应中包含一个security token。Keycloak检查response是否有效,若是有效将在keycloak建立一个新用户(若是用户已存在则跳过此步,若是IDP更新了用户信息则会同步信息),以后keycloak颁发本身的token。
Keycloak支持配置默认IDP,客户端也能够请求指定的IDP。
若要配置IDP,Keycloak须要启用SSL/HTTPS。在生产环境通常使用reverse proxy或load balancer启用HTTPS。为了演示,咱们在keycloak server中配置。
$ keytool -genkey -alias sso.itrunner.org -keyalg RSA -keystore keycloak.jks -validity 10950 Enter keystore password: Re-enter new password: What is your first and last name? [Unknown]: sso.itrunner.org What is the name of your organizational unit? [Unknown]: itrunner What is the name of your organization? [Unknown]: itrunner What is the name of your City or Locality? [Unknown]: Beijing What is the name of your State or Province? [Unknown]: Beijing What is the two-letter country code for this unit? [Unknown]: CN Is CN=sso.itrunner.org, OU=itrunner, O=itrunner, L=Beijing, ST=Beijing, C=CN correct? [no]: yes Enter key password for <sso.itrunner.org> (RETURN if same as keystore password): Re-enter new password:
将keycloak.jks拷贝到configuration/目录,链接Jboss CLI后执行如下命令建立新的security-realm:
$ /core-service=management/security-realm=UndertowRealm:add() $ /core-service=management/security-realm=UndertowRealm/server-identity=ssl:add(keystore-path=keycloak.jks, keystore-relative-to=jboss.server.config.dir, keystore-password=secret)
修改https-listener使用新建立的realm:
$ /subsystem=undertow/server=default-server/https-listener=https:write-attribute(name=security-realm, value=UndertowRealm)
下面介绍如何配置SAML 2.0协议的ADFS和Salesforce IDP。
配置Keycloak Identity Provider
Identity Providers -> Add provider -> SAML v2.0:
填入Alias、Display Name后滚动到底部,导入ADFS FederationMetadata:
ADFS FederationMetadata地址为:https://adfs.domain.name/FederationMetadata/2007-06/FederationMetadata.xml ,也能够保存后从文件导入。
导入成功后,NameID Policy Format选择Email,启用Want AuthnRequests Signed和Validate Signature,SAML Signature Key Name选择CERT_SUBJECT。
保存后配置映射关系email、firstName、lastName,使ADFS和Keycloak的用户信息相对应:
Mapper Type选择Attribute Importer,Attribute Name分别为:
email -> http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress
firstName -> http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname
lastName -> http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname
配置ADFS
先从IDP获取SAML descriptor:https://sso.itrunner.org:8443/auth/realms/heroes/broker/adfs/endpoint/descriptor ,也能够从Identity Provider -> Export下载。
进入AD FS管理控制台,右击Relying Party Trusts -> Add Relying Party Trust:
选择Claims aware -> Start:
导入以前的descriptor XML文件。
输入Display Name,接下来的设置保持默认值。
咱们须要配置两个Rule:Name ID和User属性。在弹出的Edit Claim Issuance Policy窗口中点击Add Rule:
Name ID的rule template选择Transform an incoming claim:
User属性的rule template选择Send LDAP attributes as Claims,而后添加如下属性:
说明:若是ADFS为自签名证书,须要将证书导入Java truststore
前提,Salesforce已启用Identity Provider并分配了域名。若是未启用,依次进入 Setup -> Setttins -> Identity -> Identity Provider -> Enable。启用后点击Download Metadata下载Metadata。
配置Keycloak Identity Provider
Identity Providers -> Add provider -> SAML v2.0:
填入Alias、Display Name后滚动到底部,导入Salesforce Metadata:
导入成功后,NameID Policy Format选择Persistent,启用Want AuthnRequests Signed和Validate Signature,SAML Signature Key Name选择KEYI_ID。
保存后配置映射关系email、firstName、lastName:
配置Salesforce Connected App
在Salesforce Identity Provider页面,点击底部Service Providers的连接"Click here",建立新的Connected App:
接下来配置SAML,一样先从IDP获取SAML descriptor:https://sso.itrunner.org:8443/auth/realms/heroes/broker/salesforce/endpoint/descriptor ,其中包含了下面须要的内容:
保存,而后点击页面顶部的Manage,配置Profiles和Permission Sets:
最后定义Custom Attributes:firstName、lastName:
采用Keycloak结合Spring security的方式。
<dependencies> ... <dependency> <groupId>org.keycloak</groupId> <artifactId>keycloak-spring-boot-starter</artifactId> </dependency> ... </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.keycloak.bom</groupId> <artifactId>keycloak-adapter-bom</artifactId> <version>7.0.1</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
application.yml:
keycloak: cors: true cors-allowed-methods: GET,POST,DELETE,PUT,OPTIONS cors-allowed-headers: Accept,Accept-Encoding,Accept-Language,Authorization,Connection,Content-Type,Host,Origin,Referer,User-Agent,X-Requested-With
application-dev.yml
keycloak: enabled: true auth-server-url: http://localhost:8090/auth realm: heroes resource: heroes public-client: true bearer-only: true
application-prod.yml
keycloak: enabled: true auth-server-url: https://sso.itrunner.org/auth realm: heroes resource: heroes public-client: true ssl-required: all disable-trust-manager: true bearer-only: true
Keycloak提供了便利的基类KeycloakWebSecurityConfigurerAdapter来建立WebSecurityConfigurer。
package org.itrunner.heroes.config; import org.keycloak.adapters.springsecurity.KeycloakSecurityComponents; import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider; import org.keycloak.adapters.springsecurity.client.KeycloakClientRequestFactory; import org.keycloak.adapters.springsecurity.client.KeycloakRestTemplate; import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter; import org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticatedActionsFilter; import org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticationProcessingFilter; import org.keycloak.adapters.springsecurity.filter.KeycloakPreAuthActionsFilter; import org.keycloak.adapters.springsecurity.filter.KeycloakSecurityContextRequestFilter; import org.keycloak.adapters.springsecurity.management.HttpSessionManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper; import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy; import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy; @Configuration @EnableWebSecurity @ComponentScan(basePackageClasses = KeycloakSecurityComponents.class) public class WebSecurityConfig extends KeycloakWebSecurityConfigurerAdapter { private static final String ROLE_ADMIN = "ADMIN"; @Value("${management.endpoints.web.exposure.include}") private String[] actuatorExposures; @Autowired public KeycloakClientRequestFactory keycloakClientRequestFactory; @Override public void configure(WebSecurity web) { web.ignoring().antMatchers("/api-docs", "/swagger-resources/**", "/swagger-ui.html**", "/webjars/**"); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider(); SimpleAuthorityMapper grantedAuthoritiesMapper = new SimpleAuthorityMapper(); grantedAuthoritiesMapper.setConvertToUpperCase(true); keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(grantedAuthoritiesMapper); auth.authenticationProvider(keycloakAuthenticationProvider); } @Override protected void configure(HttpSecurity http) throws Exception { super.configure(http); http.csrf().disable().authorizeRequests().requestMatchers(EndpointRequest.to(actuatorExposures)).permitAll().anyRequest().hasRole(ROLE_ADMIN); } @Bean @Override protected SessionAuthenticationStrategy sessionAuthenticationStrategy() { return new NullAuthenticatedSessionStrategy(); } @Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) public KeycloakRestTemplate keycloakRestTemplate() { return new KeycloakRestTemplate(keycloakClientRequestFactory); } @Bean public FilterRegistrationBean keycloakAuthenticationProcessingFilterRegistrationBean(KeycloakAuthenticationProcessingFilter filter) { FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter); registrationBean.setEnabled(false); return registrationBean; } @Bean public FilterRegistrationBean keycloakPreAuthActionsFilterRegistrationBean(KeycloakPreAuthActionsFilter filter) { FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter); registrationBean.setEnabled(false); return registrationBean; } @Bean public FilterRegistrationBean keycloakAuthenticatedActionsFilterBean(KeycloakAuthenticatedActionsFilter filter) { FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter); registrationBean.setEnabled(false); return registrationBean; } @Bean public FilterRegistrationBean keycloakSecurityContextRequestFilterBean(KeycloakSecurityContextRequestFilter filter) { FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter); registrationBean.setEnabled(false); return registrationBean; } @Bean @Override @ConditionalOnMissingBean(HttpSessionManager.class) protected HttpSessionManager httpSessionManager() { return new HttpSessionManager(); } }
说明:
@Service public class RemoteProductService { @Autowired private KeycloakRestTemplate template; private String endpoint; public List<String> getProducts() { ResponseEntity<String[]> response = template.getForEntity(endpoint, String[].class); return Arrays.asList(response.getBody()); } }
默认,Keycloak Spring Security Adapter将查找keycloak.json配置文件, 为确保使用Keycloak Spring Boot Adapter的配置增长KeycloakSpringBootConfigResolver:
@SpringBootApplication @EnableJpaRepositories(basePackages = {"org.itrunner.heroes.repository"}) @EntityScan(basePackages = {"org.itrunner.heroes.domain"}) @EnableJpaAuditing public class HeroesApplication { public static void main(String[] args) { SpringApplication.run(HeroesApplication.class, args); } @Bean public KeycloakSpringBootConfigResolver KeycloakConfigResolver() { return new KeycloakSpringBootConfigResolver(); } }
工具类,从SecurityContext Authentication中获取登陆用户的信息。
package org.itrunner.heroes.util; import org.keycloak.adapters.RefreshableKeycloakSecurityContext; import org.keycloak.representations.AccessToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import java.util.Optional; import static java.util.Optional.empty; import static java.util.Optional.of; public class KeycloakContext { private KeycloakContext() { } public static Optional<AccessToken> getAccessToken() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null || !authentication.isAuthenticated() || !(authentication.getCredentials() instanceof RefreshableKeycloakSecurityContext)) { return empty(); } return of(((RefreshableKeycloakSecurityContext) authentication.getCredentials()).getToken()); } public static Optional<String> getUsername() { Optional<AccessToken> accessToken = getAccessToken(); return accessToken.map(AccessToken::getPreferredUsername); } public static Optional<String> getEmail() { Optional<AccessToken> accessToken = getAccessToken(); return accessToken.map(AccessToken::getEmail); } }
调用Keycloak token endpoint获取access token,而后添加到BearerAuth Header。
@Before public void setup() { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); map.add("grant_type", "password"); map.add("client_id", "heroes"); map.add("username", "admin"); map.add("password", "admin"); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(map, requestHeaders); Map<String, String> response = restTemplate.postForObject("http://localhost:8090/auth/realms/heroes/protocol/openid-connect/token", requestEntity, Map.class); String token = response.get("access_token"); restTemplate.getRestTemplate().setInterceptors( Collections.singletonList((request, body, execution) -> { HttpHeaders headers = request.getHeaders(); headers.setBearerAuth(token); return execution.execute(request, body); })); }
使用MockMvc进行测试的小伙伴,可使用下面定义的WithMockKeycloakUser注解来mock KeycloakSecurityContext:
WithMockKeycloakUser
package org.itrunner.heroes.base; import org.springframework.security.test.context.support.WithSecurityContext; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) @WithSecurityContext(factory = WithMockCustomUserSecurityContextFactory.class) public @interface WithMockKeycloakUser { String username() default "admin"; String email() default "admin@itrunner.org"; String[] roles() default {"USER", "ADMIN"}; }
WithMockCustomUserSecurityContextFactory
package org.itrunner.heroes.base; import org.keycloak.KeycloakPrincipal; import org.keycloak.adapters.RefreshableKeycloakSecurityContext; import org.keycloak.adapters.spi.KeycloakAccount; import org.keycloak.adapters.springsecurity.account.KeycloakRole; import org.keycloak.adapters.springsecurity.account.SimpleKeycloakAccount; import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken; import org.keycloak.representations.AccessToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.test.context.support.WithSecurityContextFactory; import java.util.ArrayList; import java.util.HashSet; import java.util.List; public class WithMockCustomUserSecurityContextFactory implements WithSecurityContextFactory<WithMockKeycloakUser> { @Override public SecurityContext createSecurityContext(WithMockKeycloakUser keycloakUser) { AccessToken accessToken = new AccessToken(); accessToken.setPreferredUsername(keycloakUser.username()); accessToken.setEmail(keycloakUser.email()); accessToken.expiration(Integer.MAX_VALUE); accessToken.type("Bearer"); RefreshableKeycloakSecurityContext keycloakSecurityContext = new RefreshableKeycloakSecurityContext(null, null, "access-token-string", accessToken, null, null, null); KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = new KeycloakPrincipal<>("user-id", keycloakSecurityContext); HashSet<String> roles = new HashSet<>(); List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String role : keycloakUser.roles()) { roles.add(role); grantedAuthorities.add(new KeycloakRole(role)); } KeycloakAccount account = new SimpleKeycloakAccount(principal, roles, keycloakSecurityContext); Authentication auth = new KeycloakAuthenticationToken(account, false, grantedAuthorities); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(auth); return context; } }
用法:
@Test @WithMockKeycloakUser(username = "username", email = "email") public void testMethod() { ... }
引入keycloak-js,版本要与Keycloak Server一致。
... "keycloak-js": "7.0.1", ...
KeycloakService建立Keycloak实例,提供与Keycloak交互的基本方法。
import {Injectable} from '@angular/core'; import {HttpHeaders} from '@angular/common/http'; import {Observable} from 'rxjs'; import {ExcludedUrl, ExcludedUrlRegex, KeycloakOptions} from './keycloak-options'; import * as Keycloak from 'keycloak-js'; @Injectable({providedIn: 'root'}) export class KeycloakService { private keycloak: Keycloak.KeycloakInstance; private userProfile: Keycloak.KeycloakProfile; private loadUserProfileAtStartUp: boolean; private _enableBearerInterceptor: boolean; private _excludedUrls: ExcludedUrlRegex[]; /** * Keycloak initialization. It should be called to initialize the adapter. * Options is a object with 2 main parameters: config and initOptions. The first one will be used to create the Keycloak instance. * The second one are options to initialize the keycloak instance. * * @param options * Config: may be a string representing the keycloak URI or an object with the following content: * - url: Keycloak json URL * - realm: realm name * - clientId: client id * * initOptions: * - onLoad: Specifies an action to do on load. Supported values are '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). * - responseMode: Set the OpenID Connect response mode send to Keycloak server at login request. * Valid values are query or fragment . Default value is fragment, which means that after successful authentication will Keycloak redirect to * javascript application with OpenID Connect parameters added in URL fragment. This is generally safer and recommended over query. * - flow: Set the OpenID Connect flow. Valid values are standard, implicit or hybrid. * * enableBearerInterceptor: Flag to indicate if the bearer will added to the authorization header. * * loadUserProfileInStartUp: Indicates that the user profile should be loaded at the keycloak initialization, just after the login. * * bearerExcludedUrls: String Array to exclude the urls that should not have the Authorization Header automatically added. * * @returns A Promise with a boolean indicating if the initialization was successful. */ init(options: KeycloakOptions = {}): Promise<boolean> { return new Promise((resolve, reject) => { this.initServiceValues(options); const {config, initOptions} = options; this.keycloak = Keycloak(config); this.keycloak.init(initOptions) .then(async authenticated => { if (authenticated && this.loadUserProfileAtStartUp) { await this.loadUserProfile(); } resolve(authenticated); }) .catch((kcError) => { let msg = 'An error happened during Keycloak initialization.'; if (kcError) { msg = msg.concat(`\nAdapter error details:\nError: ${kcError.error}\nDescription: ${kcError.error_description}` ); } reject(msg); }); }); } /** * Loads all bearerExcludedUrl content in a uniform type: ExcludedUrl, * so it becomes easier to handle. * * @param bearerExcludedUrls array of strings or ExcludedUrl that includes * the url and HttpMethod. */ private loadExcludedUrls(bearerExcludedUrls: (string | ExcludedUrl)[]): ExcludedUrlRegex[] { const excludedUrls: ExcludedUrlRegex[] = []; for (const item of bearerExcludedUrls) { let excludedUrl: ExcludedUrlRegex; if (typeof item === 'string') { excludedUrl = {urlPattern: new RegExp(item, 'i'), httpMethods: []}; } else { excludedUrl = { urlPattern: new RegExp(item.url, 'i'), httpMethods: item.httpMethods }; } excludedUrls.push(excludedUrl); } return excludedUrls; } /** * Handles the class values initialization. */ private initServiceValues({enableBearerInterceptor = true, loadUserProfileAtStartUp = true, bearerExcludedUrls = []}): void { this._enableBearerInterceptor = enableBearerInterceptor; this.loadUserProfileAtStartUp = loadUserProfileAtStartUp; this._excludedUrls = this.loadExcludedUrls(bearerExcludedUrls); } /** * Redirects to login form */ login(options: Keycloak.KeycloakLoginOptions = {}): Promise<void> { return new Promise((resolve, reject) => { this.keycloak.login(options) .then(async () => { if (this.loadUserProfileAtStartUp) { await this.loadUserProfile(); } resolve(); }) .catch(() => reject(`An error happened during the login.`)); }); } /** * Redirects to logout. * * @param redirectUri Specifies the uri to redirect to after logout. * @returns A void Promise if the logout was successful, cleaning also the userProfile. */ logout(redirectUri?: string): Promise<void> { return new Promise((resolve, reject) => { const options: any = {redirectUri}; this.keycloak.logout(options) .then(() => { this.userProfile = undefined; resolve(); }) .catch(() => reject('An error happened during logout.')); }); } /** * Redirects to the Account Management Console */ account() { this.keycloak.accountManagement(); } /** * Check if the user has access to the specified role. * * @param role role name * @param resource resource name If not specified, `clientId` is used * @returns A boolean meaning if the user has the specified Role. */ hasRole(role: string, resource?: string): boolean { let hasRole: boolean; hasRole = this.keycloak.hasResourceRole(role, resource); if (!hasRole) { hasRole = this.keycloak.hasRealmRole(role); } return hasRole; } /** * Check if user is logged in. * * @returns A boolean that indicates if the user is logged in. */ async isLoggedIn(): Promise<boolean> { try { if (!this.keycloak.authenticated) { return false; } await this.updateToken(20); return true; } catch (error) { return false; } } /** * Returns true if the token has less than minValidity seconds left before it expires. * * @param minValidity Seconds left. (minValidity) is optional. Default value is 0. * @returns Boolean indicating if the token is expired. */ isTokenExpired(minValidity: number = 0): boolean { return this.keycloak.isTokenExpired(minValidity); } /** * If the token expires within minValidity seconds the token is refreshed. If the * session status iframe is enabled, the session status is also checked. * Returns a promise telling if the token was refreshed or not. If the session is not active * anymore, the promise is rejected. * * @param minValidity Seconds left. (minValidity is optional, if not specified 5 is used) * @returns Promise with a boolean indicating if the token was successfully updated. */ updateToken(minValidity: number = 5): Promise<boolean> { return new Promise(async (resolve, reject) => { if (!this.keycloak) { reject('Keycloak Angular library is not initialized.'); return; } this.keycloak.updateToken(minValidity) .then(refreshed => { resolve(refreshed); }) .catch(() => reject('Failed to refresh the token, or the session is expired')); }); } /** * Returns the authenticated token, calling updateToken to get a refreshed one if * necessary. If the session is expired this method calls the login method for a new login. * * @returns Promise with the generated token. */ getToken(): Promise<string> { return new Promise(async (resolve) => { try { await this.updateToken(10); resolve(this.keycloak.token); } catch (error) { this.login(); } }); } /** * Loads the user profile. * Returns promise to set functions to be invoked if the profile was loaded * successfully, or if the profile could not be loaded. * * @param forceReload * If true will force the loadUserProfile even if its already loaded. * @returns * A promise with the KeycloakProfile data loaded. */ loadUserProfile(forceReload: boolean = false): Promise<Keycloak.KeycloakProfile> { return new Promise(async (resolve, reject) => { if (this.userProfile && !forceReload) { resolve(this.userProfile); return; } if (!this.keycloak.authenticated) { reject('The user profile was not loaded as the user is not logged in.'); return; } this.keycloak.loadUserProfile() .then(result => { this.userProfile = result as Keycloak.KeycloakProfile; resolve(this.userProfile); }) .catch(() => reject('The user profile could not be loaded.')); }); } /** * Returns the logged username. */ getUsername(): string { if (!this.userProfile) { throw new Error('User not logged in or user profile was not loaded.'); } return this.userProfile.username; } /** * Returns email of the logged user */ getUserEmail(): string { if (!this.userProfile) { throw new Error('User not logged in or user profile was not loaded.'); } return this.userProfile.email; } /** * Clear authentication state, including tokens. This can be useful if application * has detected the session was expired, for example if updating token fails. * Invoking this results in onAuthLogout callback listener being invoked. */ clearToken(): void { this.keycloak.clearToken(); } /** * Adds a valid token in header. The key & value format is: Authorization Bearer <token>. * If the headers param is undefined it will create the Angular headers object. * * @param headers Updated header with Authorization and Keycloak token. * @returns An observable with the HTTP Authorization header and the current token. */ addTokenToHeader(headers: HttpHeaders = new HttpHeaders()): Observable<HttpHeaders> { return new Observable((observer) => { this.getToken().then(token => { headers = headers.set('Authorization', 'bearer ' + token); observer.next(headers); observer.complete(); }).catch(error => { observer.error(error); }); }); } get enableBearerInterceptor(): boolean { return this._enableBearerInterceptor; } get excludedUrls(): ExcludedUrlRegex[] { return this._excludedUrls; } }
建立Keycloak实例时若未提供config参数,则将使用keycloak.json。为适用不一样的环境,咱们在environment中配置Keycloak参数。
environment.ts
export const environment = { production: false, apiUrl: 'http://localhost:8080', keycloak: { config: { url: 'http://localhost:8090/auth', realm: 'heroes', clientId: 'heroes', sslRequired: 'external' }, initOptions: { onLoad: 'login-required', checkLoginIframe: false, promiseType: 'native' }, enableBearerInterceptor: true, loadUserProfileAtStartUp: true, bearerExcludedUrls: ['/assets'] } };
environment.prod.ts
export const environment = { production: true, apiUrl: 'http://heroes-api.apps.itrunner.org', keycloak: { config: { url: 'https://sso.itrunner.org/auth', realm: 'heroes', clientId: 'heroes', sslRequired: 'all' }, initOptions: { onLoad: 'login-required', checkLoginIframe: false, promiseType: 'native' }, enableBearerInterceptor: true, loadUserProfileAtStartUp: true, bearerExcludedUrls: ['/assets'] } };
参数说明:
为HTTP请求添加bearer token。
import {Injectable} from '@angular/core'; import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http'; import {Observable} from 'rxjs'; import {KeycloakService} from './keycloak.service'; import {mergeMap} from 'rxjs/operators'; import {ExcludedUrlRegex} from './keycloak-options'; @Injectable() export class KeycloakBearerInterceptor implements HttpInterceptor { constructor(private keycloakService: KeycloakService) { } intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const {enableBearerInterceptor, excludedUrls} = this.keycloakService; if (!enableBearerInterceptor) { return next.handle(req); } const shallPass: boolean = excludedUrls.findIndex(item => this.isUrlExcluded(req, item)) > -1; if (shallPass) { return next.handle(req); } return this.keycloakService.addTokenToHeader(req.headers).pipe( mergeMap(headersWithBearer => { const kcReq = req.clone({headers: headersWithBearer}); return next.handle(kcReq); }) ); } /** * Checks if the url is excluded from having the Bearer Authorization header added. * * @param req http request from @angular http module. * @param excludedUrlRegex contains the url pattern and the http methods, * excluded from adding the bearer at the Http Request. */ private isUrlExcluded({method, url}: HttpRequest<any>, {urlPattern, httpMethods}: ExcludedUrlRegex): boolean { const httpTest = httpMethods.length === 0 || httpMethods.join().indexOf(method.toUpperCase()) > -1; const urlTest = urlPattern.test(url); return httpTest && urlTest; } }
import {Injectable} from '@angular/core'; import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router'; import {KeycloakService} from './keycloak.service'; @Injectable({providedIn: 'root'}) export class CanActivateAuthGuard implements CanActivate { constructor(private router: Router, private keycloakService: KeycloakService) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> { return new Promise(async (resolve) => { const authenticated = await this.keycloakService.isLoggedIn(); if (authenticated) { resolve(true); } else { this.keycloakService.login(); resolve(false); } }); } }
为提升性能,在app.module.ts中初始化KeycloakService。
... export function initKeycloak(keycloak: KeycloakService): () => Promise<any> { return (): Promise<any> => { return new Promise(async (resolve, reject) => { try { // @ts-ignore await keycloak.init(environment.keycloak); resolve(); } catch (error) { reject(error); } }); }; } ... providers: [ [ {provide: APP_INITIALIZER, useFactory: initKeycloak, deps: [KeycloakService], multi: true}, {provide: HTTP_INTERCEPTORS, useClass: KeycloakBearerInterceptor, multi: true}, ... ] ], ...
Angular与Keycloak集成完毕,启动服务后访问页面会自动跳转到Keycloak登陆界面:
用户能够直接输入用户名/密码、能够选择IDP登陆。
配置Keycloak IDP时能够控制是否在登陆界面显示,认证流程中能够设置默认IDP,客户端调用时能够指定IDP,多种方式灵活组合能够知足不一样需求。
指定IDP,Angular调用时仅需指定idpHint参数,其值为IDP的alias:
keycloakService.login({idpHint: 'adfs'});
Keycloak
AD FS Docs
Salesforce Identity Providers and Service Providers
A Quick Guide to Using Keycloak with Spring Boot
How to Setup MS AD FS 3.0 as Brokered Identity Provider in Keycloak