Spring Boot/Angular整合Keycloak实现单点登录功能
Keycloak
Keycloak为现代应用和服务提供开源的认证和访问管理,即通常所说的认证和授权。Keycloak支持OpenID、OAuth2.0和SAML2.0协议;支持用户注册、用户管理、权限管理;支持代理OpenID、SAML2.0IDP,支持GitHub、LinkedIn等第三方登录,支持整合LDAP和ActiveDirectory;支持自定义认证流程、自定义用户界面,支持国际化。
Keycloak支持Java、C#、Python、Android、iOS、JavaScript、Nodejs等平台或语言,提供简单易用的Adapter,仅需少量配置和代码即可实现SSO。
Keycloak新的发行版命名为Quarkus,专为GraalVM和OpenJDKHotSpot量身定制的一个KurbernetesNativeJava框架,计划2019年底正式发布。
安装
Keycloak构建在WildFlyapplicationserver之上,从官网下载Standaloneserverdistribution解压后运行bin/standalone.sh即可启动。默认使用h2数据库,可以修改配置使用其它数据库。StandaloneClusteredMode、DomainClusteredMode启动模式和更多配置请参阅官方文档。
默认,本地网址为http://localhost:8080/auth,首次登录时必须创建admin用户:
Realm
allrequests所有请求都需通过HTTPS访问externalrequestslocalhost和私有IP不需通过HTTPS访问none任何客户端都不需HTTPS
ThemesTab可以配置界面主题、启用国际化:
Client
Client是realm中受信任的应用。
account账户管理
admin-clibrokerrealm-management预置了realm管理角色,创建realm管理员时需要分配这些角色security-admin-consolerealm管理控制台
创建heroesclient,点击Clients右上方的Create:
ClientProtocol使用默认值openid-connect。AccessType有三个选项confidential、public、bearer-only,保持默认值public。confidential需要clientsecret,但我们将在web应用中使用此client,无法以安全的方式传输secret,必须使用publicclient,只要严格使用HTTPS,可以保证安全。ValidRedirectURIs输入http://localhost:4200/*。
认证流程:
- StandardFlow即OAuth2.0规范中的AuthorizationCodeFlow,推荐使用的认证流程,安全性高。keycloak验证用户后附加一次性、临时的AuthorizationCode重定向到浏览器,浏览器凭此Code与keycloak交换token(identity、access和refreshtoken)
- ImplicitFlowkeycloak验证用户后直接返回identity和accesstoken
- DirectAccessGrantsRESTclient获取token的方式,使用HTTPPost请求,响应结果包含access和refreshtoken
调用示例,请求地址:http://localhost:8080/auth/realms/heroes/protocol/openid-connect/token:
ClientScope
ClientScope定义了协议映射关系,keycloak预定义了一些Scope,每个client会自动继承,这样就不必在client内重复定义mapper了。ClientScope分为default和optional两种,defaultscope会自动生效,optionalscope指定使用时才生效。
启用optionalscope需要使用scope参数:
启用相应scope或配置mapper后,才能在client的token或userinfo中显示相应的属性。比如,上图中我们启用了phonescope,phonemapper中定义了phonenumber:
如果用户属性中定义了phoneNumber,在token中则会显示phone_number,可以在heroesclient->ClientScopes->Evaluate查看效果:
Role、Group、User
Role
Role分为两种级别:Realm、Client,默认RealmRole:offline_access、uma_authorization。
offlineaccess
OpenID规范中定义了offlineaccess,用户登录获得offlinetoken,当用户退出后offlinetoken仍可使用。在很多场景中是非常有用的,比如每日离线备份数据。要获得offlinetoken除需offline_access角色外,还需指定offline_accessScope。默认,offlinetoken不会过期,但需每30天刷新一次。offlinetoken可以撤销:
Keycloak预定义了Browser、DirectGrant、Registration、ResetCredentials等认证流程,用户也可以自定义。以Brower流程为例:
IdentityProviderADFSSalesforceSpringBootAngular参考文档
KeycloakAQuickGuidetoUsingKeycloakwithSpringBootADFSDocsSpringBootandOAuth2OAuth2.0LoginSampleSpringBootandOAuth2withKeycloakSpringSAMLSpringbootOauth2Server搭建Oauth2认证服务HowtoSetupMSADFS3.0asBrokeredIdentityProviderinKeycloak
总结
以上所述是小编给大家介绍的SpringBoot/Angular整合Keycloak实现单点登录功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。