我对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'中配置的一样。 –