是否可以通过证书仅保护一个 Spring Boot Rest 端点?

2024-05-04

有关架构的一些信息: - 我们正在 Cloud Foundry 中运行(使用 https 路由) - 我们有一个网关(Spring Cloud Netflix zuul) - 我们的应用程序由令牌进行内部保护

如果您需要其他信息,请询问。

现在我们想要保护网关的一条路由(api/v1/authorizations)通过证书。这样只有拥有此证书的客户端才能调用此端点。

那可能吗?


我将把你的问题分成两部分,因为它们是 Spring Security 的两个不同的问题。

是否可以仅保护一个 Spring Boot Rest 端点

是的,您可以对 Spring Security 配置进行大量自定义。可以打开除一个端点之外的所有端点。也可以混合使用,因此有些对所有人开放,有些由方法 A(可能是密码)保护,另一些由方法 B(可能是证书)保护。

这是一个简单的示例,其中您混合了 open (/css/**)和安全端点(/user/**).

protected void configure(HttpSecurity http) throws Exception {
            http
            .authorizeRequests(authorizeRequests ->
                authorizeRequests
                    .antMatchers("/css/**", "/index").permitAll()
                    .antMatchers("/user/**").hasRole("USER")
            )
            .formLogin(formLogin ->
                formLogin
                    .loginPage("/login")
                    .failureUrl("/login-error")
            );
}

From: https://github.com/spring-projects/spring-security/blob/master/samples/boot/helloworld/src/main/java/org/springframework/security/samples/config/SecurityConfig.java#L34-L44 https://github.com/spring-projects/spring-security/blob/master/samples/boot/helloworld/src/main/java/org/springframework/security/samples/config/SecurityConfig.java#L34-L44

通过证书?

绝对地。 Spring Security 支持通过 x.509 证书进行身份验证。

https://docs.spring.io/spring-security/site/docs/5.1.6.RELEASE/reference/htmlsingle/#x509 https://docs.spring.io/spring-security/site/docs/5.1.6.RELEASE/reference/htmlsingle/#x509

以下是使用 Spring Security 配置 x.509 身份验证的示例。

    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .x509()
                .subjectPrincipalRegex("OU=(.*?)(?:,|$)")
                .and()
            .authorizeRequests()
                .mvcMatchers("/admin/**").hasRole("ADMIN")
                .mvcMatchers("/noauth").permitAll()
                .anyRequest().authenticated();
        // @formatter:on
    }

From: https://github.com/nebhale/mtls-sample/blob/master/server/src/main/java/io/pivotal/mtlssample/server/ServerApplication.java#L96-L105 https://github.com/nebhale/mtls-sample/blob/master/server/src/main/java/io/pivotal/mtlssample/server/ServerApplication.java#L96-L105

前三行配置身份验证以使用 x509 证书。其余四行配置授权以要求管理员用户访问/admin/**,允许任何人访问/noauth,并要求任何经过身份验证的用户访问其他内容。

要在 Cloud Foundry 上运行,您无需在应用程序中执行任何特殊操作,但您的平台运营商需要启用 mTLS 支持。您可以查看我上面放置的客户端和服务器测试的完整演示,以及在 Cloud Foundry 上运行的说明。

https://github.com/nebhale/mtls-sample https://github.com/nebhale/mtls-sample

希望有帮助!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是否可以通过证书仅保护一个 Spring Boot Rest 端点? 的相关文章

随机推荐