gpt4 book ai didi

spring - @EnableOAuth2Sso - 如何保护/取消保护资源?

转载 作者:行者123 更新时间:2023-12-04 21:13:02 26 4
gpt4 key购买 nike

我正在尝试在 Spring Cloud Security 中使用 @EnableOAuth2Sso 功能。具体来说,我试图用 OAuth2 保护一些资源,同时让其他资源可公开访问。我已经设法让这个工作,但我正在查看生成的代码并想知道是否有更干净的方法。

我正在关注这里的文档:https://github.com/spring-cloud/spring-cloud-security/blob/master/src/main/asciidoc/spring-cloud-security.adoc以及来自 Spring Boot 引用的类似指导。我有一个很小的代码示例来说明我的困境:https://github.com/kennyk65/oAuthSsoExample .

简而言之,我希望 localhost:8080/unprotected 资源公开可用,并且我希望 localhost:8080/protected 资源需要 OAuth2(通过 github,按配置)。我能够让基本的 OAuth2 行为正常工作,但导致/unprotected 公开可用是有问题的。

首先,文档表明您可以只使用 OAuth2SsoConfigurer 的 match() 方法来指定要保护的资源。我发现这不起作用;当我尝试时,我收到一个 IllegalStateException 说至少需要一个映射。这似乎是指未实现的 configure(HttpSecurity) 方法。

接下来,我尝试在 configure(HttpSecurity) 中指定一个映射,声明“不 protected ”的资源应该不 protected 。但是,这会导致对该资源应用 Http 基本安全性。奇怪的是,这导致“ protected ”资源完全公开!

// This results in “unprotected” being protected by HTTP Basic
// and “protected” being completely open!
@Configuration
protected static class OauthConfig extends OAuth2SsoConfigurerAdapter {
@Override
public void match(RequestMatchers matchers) {
matchers.antMatchers("/protected/**");
}

@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/unprotected/**").permitAll();
}
}

一时兴起,我特意添加了应该对 protected 资源进行身份验证的内容。这导致 protected 资源获得 OAuth2 保护(万岁!)但未 protected 资源应用了 http 基本安全性(嗯?)。
// This results in “protected” being protected by OAuth 2
// and “unprotected” being protected by HTTP Basic, even though we say permitAll():
@Configuration
protected static class OauthConfig extends OAuth2SsoConfigurerAdapter {
@Override
public void match(RequestMatchers matchers) {
matchers.antMatchers("/protected/**");
}

@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/protected/**”).authenticated();
.antMatchers("/unprotected/**").permitAll();
}
}

为了尝试找到神奇的组合,我尝试使用 security.basic.enabled: false 简单地关闭 HTTP 基本身份验证。这有效(万岁!),尽管我仍然有点困惑映射的问题是什么。

所以我想我的问题是,这是正确的吗?使用 OAuth 2 保护某些资源并让其他资源不受打扰的最佳方法是什么?

最佳答案

如果您在 /protected/** 上匹配那么再向 /unprotected/** 添加访问规则是没有意义的。 (路径不匹配,因此永远不会应用规则)。您需要为“未 protected ”资源使用另一个过滤器链,或者为 SSO 提供更广泛的匹配。在前一种情况下,如果您不介意关闭它提供的安全性,那么您从 Spring Security 获得的默认安全性就可以了。例如。

@Configuration
protected static class OauthConfig extends OAuth2SsoConfigurerAdapter {
@Override
public void match(RequestMatchers matchers) {
matchers.antMatchers("/protected/**");
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**”).authenticated();
}
}

并设置 security.basic.enabled=false .

关于spring - @EnableOAuth2Sso - 如何保护/取消保护资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30491980/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com