我對Spring很感興趣,並且試圖使用spring-security-oauth2構建OAuth服務器。spring-security-oauth2中的HttpSecurity配置問題
我主要引用spring.io給出的示例和教程。
https://github.com/spring-projects/spring-security-oauth/tree/master/samples/oauth2 http://spring.io/guides/tutorials/spring-boot-oauth2/
不過,我面對約HttpSecurity
配置一些問題。
我的文件夾結構如下。
├─java
│ └─com
│ └─example
│ Greeting.java
│ GreetingController.java
│ MvcConfig.java
│ OAuth2ServerConfig.java
│ SecurityConfig.java
│ SocialApplication.java
│
└─resources
│ application.yml
│
└─templates
hello.html
home.html
login.html
我加入SecurityConfig.java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
}
OK一些HttpSecurity
配置,它工作正常。但是,我想在我的Resource Server
中保護greeting
API(這是我從另一個演示中複製的簡單休息API)。 所以我加入一些HttpSecurity
配置OAuth2ServerConfig.java
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId(RESOURCE_ID);
}
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.requestMatchers().antMatchers("/greeting")
.and()
.authorizeRequests()
.anyRequest().access("#oauth2.hasScope('scope1')");
// @formatter:on
}
}
看來我只能保護/greeting
。但是,當這樣做完成時,我甚至無法訪問/
和/login
。它說,Full authentication is required to access this resource
。
我錯過了一些配置或做錯了什麼?
我改變了你說的代碼。 '/ greeting'現在受到保護,但我在'SecurityConfig.java'中的配置不起作用。我可以在不登錄的情況下訪問'/ hello'。 –
您在添加OAuth配置之前無法做到這一點? –
我不能,當我嘗試訪問沒有登錄的'/ hello'時,它應該重定向到'/ login',就像我在'SecurityConfig.java'中配置的一樣。 –