用户身份验证是 Web 应用程序中的一项基本功能,因此人们可以创建和访问自己的帐户,但不幸的是,身份验证并不总是很容易设置,可能经常错误地实现登录和注销功能。
本教程将介绍如何使用IDaaS身份服务,用差不多3分钟的时间,为应用快速的添加一个现代的身份服务,它能让我们在 Spring 应用中轻松处理用户数据和授权。
本节介绍如何使用Spring Boot快速与OneAuth集成,将OneAuth作为WEB应用程序的用户存储库并实现用户登录。
准备工作
前提条件:
已经具备了OneAuth的组织账户。如果没有?免费创建OneAuth开发者账户
具备基础的WEB应用程序的开发经验
已有或新建的Web应用程序或项目,需要集成认证流程
请求的示例
请求授权的的示例,类似如下
https://{yourSubDomain}.oneauth.cn/v1/oauth/authorize?response_type=code&client_id=CLIENT_ID&redirect_uri=CALLBACK_URL&scope=read
以下配置将在OneAuth控制台完成,配置CALLBACK_URL 和生成CLIENT_ID
创建一个OneAuth Web应用
1. 登录OneAuth组织账户的控制台添加应用
选择【应用】-【应用】-创建应用认证方式选择OIDC,应用类型选择Web应用,点击【下一步】
2. 填写应用的登录重定向地址,
http://localhost:8000/login/oauth2/code/oneauth
当用户成功认证后,OIDC 授权服务器向Client返回的redirect_uri由该地址指定。详细参考OIDC 授权码模式
3.【保存】后,OneAuth将为该应用生成Clinet ID和Client Secret,后续在Java Spring Boot的配置中会用到这两个参数值
创建和配置Spring Boot应用
如果您想快速开始,只需下载一个应用示例,请下载我们Spring Boot示例
1.您需要将一些依赖项添加到pom.xml
添加后,Spring Security 5的OAuth配置才能正确初始化。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.将src/main/resources/application.properties重命名为src/main/resources/application.yml
在下面的代码中填写:
yourSubDomain:在注册时,OneAuth提供的租户的二级域名前缀
ClientID: 填写创建应用时,Step 2过程中OneAuth管理后台生成的Client ID
Secret: 填写创建应用时,Step 2过程中OneAuth管理后台生成的Client Secret
server:
port: 8000
spring:
thymeleaf:
cache:false
security:
oauth2:
client:
registration:
oneauth:
client-name: oneauth
client-id: {clientId}
client-secret: {clientSecret}
redirect-uri:'{baseUrl}/login/oauth2/code/{registrationId}'
client-authentication-method: post
scope:
- openid
- profile
provider:
oneauth:
issuer-uri: https://{yourSbuDomain}.oneauth.cn/oauth/v1
user-name-attribute:name
验证是否集成成功
1.重新启动您的应用程序,并访问
浏览器再次导航到http://localhost:8000 ,您会看到一个oneauth的链接,单击该链接可以单击oneauth登录。
2.单击oneauth链接,登录
点击后,您应该会看到一个登录屏幕。
3. 输入用户名和密码,认证完成后跳转回应用
输入用于创建帐户的凭据,登录后应该会看到类似以下的屏幕。
总结
我们通过 Spingboot 构建了一个简单的应用,利用Open ID Connect 协议并对接 OneAuth 提供的身份服务,实现了保护我们特定路由的方法。
参考