如何使用spring-boot 1.3.0.RC1为oauth2提供自定义安全性配置

时间:2015-10-26 18:07:53

标签: java spring spring-security spring-boot spring-cloud

使用Spring-Cloud Angel.SR3版本,我在https://github.com/spring-cloud-samples/sso中跟随了示例,并且使用spring-boot 1.2.6.RELEASE可以正常工作。

然而,对于spring-boot 1.3.0.RC1,oauth2的东西已经转移到spring-boot本身,下面的代码无法编译,因为类 OAuth2SsoConfigurerAdapter 不再存在。

什么是spring-boot创建等效配置的唯一方法?

public static void main(String[] args) {
    SpringApplication.run(MainAppApplication.class, args);
}

...

@Component
public static class LoginConfigurer extends OAuth2SsoConfigurerAdapter  {

    @Override
    public void match(RequestMatchers matchers) {
        matchers.antMatchers("/dashboard/**");
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/dashboard/**").authorizeRequests().anyRequest()
        .authenticated().and().csrf()
        .csrfTokenRepository(csrfTokenRepository()).and()
        .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
    }

    private Filter csrfHeaderFilter() {
        return new OncePerRequestFilter() {
    ...
        };
    }

    ...

}

2 个答案:

答案 0 :(得分:3)

您只需使用org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter并谨慎使用此注释org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso

我已经小心地写 因为它的行为取决于你添加它的位置。正如javadoc中所述:

  

启用OAuth2单点登录(SSO)。如果用户提供了现有的WebSecurityConfigurerAdapter并使用@ EnableOAuth2Sso进行了注释,则会通过添加身份验证过滤器和身份验证入口点来增强它。如果用户只有@ EnableOAuth2Sso而不是WebSecurityConfigurerAdapter,则会添加一个安全路径,并使用一个顺序将其置于Spring Boot的默认HTTP Basic安全链之前。

希望有所帮助!

答案 1 :(得分:2)

原来不需要特殊的适配器,只需常规 WebSecurityConfigurerAdapter 即可。如果涉及oauth2 SSO,则无法告诉下面的代码,更透明,可以说话。

@Configuration 
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
protected static class ApplicationSecurity extends WebSecurityConfigurerAdapter {

    @Autowired
    private SecurityProperties security;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
        .authorizeRequests()
            .antMatchers("/", "/ssologout").permitAll()
            .anyRequest().fullyAuthenticated()
        .and()
            .formLogin()
                .loginPage("/login").failureUrl("/login?error")
            .permitAll()
        .and()
            .logout().permitAll();
        // @formatter:on
    }

}