【发布时间】:2015-08-10 02:25:06
【问题描述】:
我正在尝试使用 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) 中指定一个映射,指出“不受保护”的资源应该不受保护。但是,这会导致将 Http 基本安全性应用于该资源。奇怪的是,这会导致“受保护”资源完全公开!
// 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();
}
}
一时兴起,我尝试故意添加应验证受保护资源的内容。这导致受保护的资源获得 OAuth2 保护(哇!),但未受保护的资源应用了 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 保护某些资源并不理会其他资源的最佳方法是什么?
【问题讨论】:
-
嗨,我看到你有类似的问题。我无法根据对您的帮助来解决它。我有 bean 学习你的课程云微服务,非常好。现在,在我从那里学到的东西之上,我正在使用 OAuth 构建安全性。你能否看看这个问题,也许你知道我错过了什么? stackoverflow.com/questions/38206714/…
标签: spring spring-security spring-boot spring-security-oauth2 spring-cloud