【发布时间】:2015-03-06 23:37:24
【问题描述】:
我们希望为 Rest Controller 应用基于 Oauth2 的安全性,而应用程序的其余部分将具有 Spring Security。这可能吗?你能提供任何例子吗?
WebSecurityConfigurerAdapter 和 ResourceServerConfigurerAdapter 似乎在两者都配置时发生冲突。
提前谢谢你。
【问题讨论】:
标签: spring-security
我们希望为 Rest Controller 应用基于 Oauth2 的安全性,而应用程序的其余部分将具有 Spring Security。这可能吗?你能提供任何例子吗?
WebSecurityConfigurerAdapter 和 ResourceServerConfigurerAdapter 似乎在两者都配置时发生冲突。
提前谢谢你。
【问题讨论】:
标签: spring-security
是的,有可能。这里给出了示例模板配置代码。请根据您的需要更改所需的配置。 关键是用不同的顺序定义配置的子静态类。在这里,我将来自\api 的任何请求视为REST API 调用。
我没有通过编译来检查代码。
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true, proxyTargetClass = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
@Order(1)
@Configuration
public static class ApiWebSecurityConfig extends OAuth2ServerConfigurerAdapter{
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//Write the AuthenticationManagerBuilder codes for the OAuth
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.antMatcher("/api/**")
.authorizeRequests()
.anyRequest().authenticated()
.and()
.apply(new OAuth2ServerConfigurer())
.tokenStore(new InMemoryTokenStore())
.resourceId(applicationName);
}
}
}
@Order(2)
@Configuration
public static class FormWebSecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
//Write the AuthenticationManagerBuilder codes for the Normal authentication
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable() //HTTP with Disable CSRF
.authorizeRequests() //Authorize Request Configuration
.anyRequest().authenticated()
.and() //Login Form configuration for all others
.formLogin()
.loginPage("/login").permitAll()
.and() //Logout Form configuration
.logout().permitAll();
}
}
}
【讨论】: