跳到主内容

Spring Security OAuth

Casdoor 可以使用 OIDC 协议作为 IDP 来连接各种应用。在本指南中,我们将以 Spring Security 为例,展示如何使用 OIDC 连接到你的应用。

步骤1:部署Casdoor​

部署 Casdoor。参见 服务器安装。确保服务器正在运行,并且你可以打开登录页面,使用 built-in/admin 和你设置的密码登录。参见 登录管理控制台。

步骤 2. 配置 Casdoor 应用​

  1. 创建一个新的Casdoor应用或使用现有的应用。
  2. 添加你的重定向 URL(你可以在下一节中找到如何获取重定向 URL 的更多详细信息)。 Casdoor Application Settings
  3. 添加所需的提供商并填写任何额外的设置。

记下应用页面中的 Client ID 和 Client secret 以供下一步使用。OIDC 发现:http://<CASDOOR_HOSTNAME>/.well-known/openid-configuration。

步骤 3. 配置 Spring Security​

Spring Security 原生支持 OIDC。

你可以自定义 Spring Security OAuth2 Client 的设置:

注意事项

把占位值换成你自己 Casdoor 实例的值(Client ID、Client secret 等)。

spring:
security:
oauth2:
client:
registration:
casdoor:
client-id: <Client ID>
client-secret: <Client Secret>
scope: openid,profile,email
authorization-grant-type: authorization_code
redirect-uri: <Redirect URL>
provider:
casdoor:
issuer-uri: http://CASDOOR_HOSTNAME
user-name-attribute: preferred_username

使用 issuer-uri 时,Spring Boot 会在启动时读取 Casdoor 的发现文档,并填充授权、令牌、用户信息 (/api/userinfo) 和 JWKS 端点。该值必须与文档中的 issuer 匹配。在 Casdoor 的用户信息中,preferred_username 是用户名,name 是显示名称。

注意事项

For the default situation of Spring Security, the <Redirect URL> should be like http://<Your Spring Boot Application Endpoint>/<Servlet Prefix if it is configured>/login/oauth2/code/casdoor, where casdoor is the registration ID. For example, in the following demo, the redirect URL should be http://localhost:8080/login/oauth2/code/casdoor.

你也应该在 casdoor 应用中配置此项。

You can also customize the settings using ClientRegistration in your code. You can find the mapping here.

步骤 4:开始使用演示​

  1. 我们可以创建一个 Spring Boot 应用。

  2. We can add a configuration that protects all endpoints except / and /login** for users to log in. Spring Security 6 removed WebSecurityConfigurerAdapter, so declare a SecurityFilterChain bean:

    @Configuration
    @EnableWebSecurity
    public class UiSecurityConfig {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
    .authorizeHttpRequests(auth -> auth
    .requestMatchers("/", "/login**").permitAll()
    .anyRequest().authenticated())
    .oauth2Login(Customizer.withDefaults());
    return http.build();
    }
    }

    有关角色映射、从 Casdoor 注销、资源服务器以及 Spring Cloud Gateway 的详细信息,请参阅 Spring Boot SSO with OpenID Connect。

  3. 我们可以为用户添加一个简单的登录页面。

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Spring OAuth Client Thymeleaf - 1</title>
    <link rel="stylesheet"
    href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" />
    </head>
    <body>
    <nav
    class="navbar navbar-expand-lg navbar-light bg-light shadow-sm p-3 mb-5">
    <a class="navbar-brand" th:href="@{/foos/}">Spring OAuth Client
    Thymeleaf - 1</a>
    </nav>
    <div class="container">
    <label>Welcome!</label> <br /> <a th:href="@{/foos/}"
    class="btn btn-primary">Login</a>
    </div>
    </body>
    </html>

    当用户点击 login 按钮时,他们将被重定向到 casdoor。

  4. 接下来,我们可以定义受保护的资源。我们可以暴露一个名为 /foos 的端点和一个用于显示的网页。

    数据模型

    public class FooModel {
    private Long id;
    private String name;

    public FooModel(Long id, String name) {
    super();
    this.id = id;
    this.name = name;
    }
    public Long getId() {
    return id;
    }
    public void setId(Long id) {
    this.id = id;
    }
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    }

    控制器

    @Controller
    public class FooClientController {
    @GetMapping("/foos")
    public String getFoos(Model model) {
    List<FooModel> foos = new ArrayList<>();
    foos.add(new FooModel(1L, "a"));
    foos.add(new FooModel(2L, "b"));
    foos.add(new FooModel(3L, "c"));
    model.addAttribute("foos", foos);
    return "foos";
    }
    }

    网页

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Spring OAuth Client Thymeleaf - 1</title>
    <link rel="stylesheet"
    href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" />
    </head>
    <body>
    <nav
    class="navbar navbar-expand-lg navbar-light bg-light shadow-sm p-3 mb-5">
    <a class="navbar-brand" th:href="@{/foos/}">Spring OAuth Client
    Thymeleaf -1</a>
    <ul class="navbar-nav ml-auto">
    <li class="navbar-text">Hi, <span sec:authentication="name">preferred_username</span>&nbsp;&nbsp;&nbsp;</li>
    </ul>
    </nav>
    <div class="container">
    <h1>All Foos:</h1>
    <table class="table table-bordered table-striped">
    <thead>
    <tr>
    <td>ID</td>
    <td>Name</td>
    </tr>
    </thead>
    <tbody>
    <tr th:if="${foos.empty}">
    <td colspan="4">No foos</td>
    </tr>
    <tr th:each="foo : ${foos}">
    <td>
    <span th:text="${foo.id}">ID</span>
    </td>
    <td>
    <span th:text="${foo.name}">Name</span>
    </td>
    </tr>
    </tbody>
    </table>
    </div>
    </body>
    </html>
注意事项

所有网页模板都应放置在 resources/templates 下。

步骤 5:尝试演示!​

在浏览器中打开 /foos;你将被重定向到 Casdoor 的登录页面。在那里或从根页面登录。

如果你访问根页面,你将看到 Casdoor 应用设置。 Casdoor Application Setting

点击 login 按钮,页面将把你重定向到 Casdoor 的登录页面。 Casdoor Application Setting

登录后,页面将把你重定向到 /foos。 Casdoor Application Setting