我最近使用 Okta 创建了一个 Spring Boot 3 + SAML 示例。希望这些说明有所帮助。
使用以下命令创建 Spring Boot 应用程序启动.spring.io https://start.spring.io。选择以下选项:
- 项目:Gradle
- 春季启动:3.0.0(快照)
- 依赖项:春季网, 春季安全, 百里香叶
Add src/main/java/com/example/demo/HomeController.java
填充经过身份验证的用户的信息。
package com.example.demo;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticatedPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomeController {
@RequestMapping("/")
public String home(@AuthenticationPrincipal Saml2AuthenticatedPrincipal principal, Model model) {
model.addAttribute("name", principal.getName());
model.addAttribute("emailAddress", principal.getFirstAttribute("email"));
model.addAttribute("userAttributes", principal.getAttributes());
return "home";
}
}
创建一个src/main/resources/templates/home.html
文件来呈现用户的信息。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity6">
<head>
<title>Spring Boot and SAML</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<h1>Welcome</h1>
<p>You are successfully logged in as <span sec:authentication="name"></span></p>
<p>Your email address is <span th:text="${emailAddress}"></span>.</p>
<p>Your authorities are <span sec:authentication="authorities"></span>.</p>
<h2>All Your Attributes</h2>
<dl th:each="userAttribute : ${userAttributes}">
<dt th:text="${userAttribute.key}"></dt>
<dd th:text="${userAttribute.value}"></dd>
</dl>
<form th:action="@{/logout}" method="post">
<button id="logout" type="submit">Logout</button>
</form>
</body>
</html>
创建一个src/main/resources/application.yml
文件来包含您的元数据 URI。
spring:
security:
saml2:
relyingparty:
registration:
assertingparty:
metadata-uri: <your-metadata-uri>
然后,改变build.gradle
to use thymeleaf-extras-springsecurity6
代替thymeleaf-extras-springsecurity5
并添加 Spring Security SAML 的依赖项:
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
implementation 'org.springframework.security:spring-security-saml2-service-provider'
要从 Okta 获取元数据 URI,请登录您的帐户并转至应用领域 > 创建应用程序集成。选择SAML 2.0然后单击Next。将您的应用程序命名为Spring Boot SAML
然后单击Next.
使用以下设置:
- 单点登录 URL:
http://localhost:8080/login/saml2/sso/okta
- 将其用于收件人 URL 和目标 URL:✅(默认值)
- 受众 URI:
http://localhost:8080/saml2/service-provider-metadata/okta
然后点击Next。选择以下选项:
- 我是 Okta 客户,正在添加内部应用程序
- 这是我们创建的内部应用程序
Select Finish.
Okta 将创建您的应用程序,您将被重定向到其Sign On标签。向下滚动到SAML 签名证书并前往SHA-2 > Actions > 查看 IdP 元数据。您可以右键单击并复制此菜单项的链接或打开其 URL。将生成的链接复制到剪贴板。它应该类似于以下内容:
https://dev-13337.okta.com/app/<random-characters>/sso/saml/metadata
转到您的应用程序任务选项卡并分配访问权限Everyone group.
将您的元数据 URI 粘贴到application.yml
文件。使用启动应用程序./gradlew bootRun
并打开http://localhost:8080
在您最喜欢的浏览器中。您应该被重定向到登录。