Spring Security Web+;OAuth2

Spring Security Web+;OAuth2,spring,spring-mvc,spring-security-oauth2,Spring,Spring Mvc,Spring Security Oauth2,我试图在同一个Spring Boot MVC应用程序中集成普通表单+会话登录和OAuth2。这可能是我对Spring安全配置工作原理的误解。我也尝试过在Sparkr示例应用程序中调整配置,但我就是做不到 我希望任何与“/web/**”匹配的url都能通过表单登录(包括重定向到登录页面)进行身份验证,但“resources/**”、“web/register”和“/login”除外 我还需要任何与“/api/**”匹配的url,以要求除“/api/register”之外的OAuth2令牌 目前似乎

我试图在同一个Spring Boot MVC应用程序中集成普通表单+会话登录和OAuth2。这可能是我对Spring安全配置工作原理的误解。我也尝试过在Sparkr示例应用程序中调整配置,但我就是做不到

我希望任何与“/web/**”匹配的url都能通过表单登录(包括重定向到登录页面)进行身份验证,但“resources/**”、“web/register”和“/login”除外 我还需要任何与“/api/**”匹配的url,以要求除“/api/register”之外的OAuth2令牌

目前似乎只有
ResourceServerConfigurerAdapter
生效。我尝试了许多规则的组合,但似乎无法达到我想要的效果。当查看调试输出时,我可以看到它试图匹配OAuth端点,然后匹配我的API端点,但不匹配任何web端点

如果我让表单登录工作,那么我需要由OAuth2保护的URL允许匿名访问。感谢您在理解/使其发挥作用方面给予的任何帮助

以下是我的配置:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/login", "/resources/**", "/web/register").permitAll()
                //.anyRequest().authenticated()
                .antMatchers("/web/**").authenticated()
                .and()
                .exceptionHandling().accessDeniedPage("/login?authorization_error=true")
                .and()
                .csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("/api/users/register")).disable()
                .logout().logoutUrl("/logout").logoutSuccessUrl("/login")
                .and()
                .formLogin().loginProcessingUrl("/login").failureUrl("/login?authorization_error=true").defaultSuccessUrl("/web/home").loginPage("/login");
    }

    @Autowired
    private CustomDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
                auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

@Configuration
public class OAuth2ServerConfig {

    private static final String TEST_RESOURCE_ID = "test";

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {
            resources.resourceId(TEST_RESOURCE_ID).stateless(false);             }

        @Override
        public void configure(HttpSecurity http) throws Exception {


            http
//                     Since we want the protected resources to be accessible in the UI as well we need
//                     session creation to be allowed (it's disabled by default in 2.0.6)
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                    .and().authorizeRequests()
                    .antMatchers("/api/users/register").permitAll()
                    .antMatchers("/api/**").access("#oauth2.isOAuth() and hasRole('ROLE_USER')")
            ;
        }
    }

    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

        @Autowired
        private TokenStore tokenStore;

        @Autowired
        private UserApprovalHandler userApprovalHandler;

        @Autowired
        @Qualifier("authenticationManagerBean")
        private AuthenticationManager authenticationManager;

        @Autowired
        private CustomUserDetailsService userDetailsService;

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients.inMemory().withClient("testapp")
                    .resourceIds(TEST_RESOURCE_ID)
                    .authorizedGrantTypes("authorization_code", "refresh_token",
                            "password")
                    .authorities("USER")
                    .scopes("read", "write")
                    .secret("secret");
        }

        @Bean
        public TokenStore tokenStore() {
            return new InMemoryTokenStore();
        }

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            endpoints
                    .tokenStore(tokenStore)
                    .userApprovalHandler(userApprovalHandler)
                    .authenticationManager(authenticationManager)
                    .userDetailsService(userDetailsService);
        }

        @Bean
        @Primary
        public DefaultTokenServices tokenServices() {
            DefaultTokenServices tokenServices = new DefaultTokenServices();
            tokenServices.setSupportRefreshToken(true);
            tokenServices.setTokenStore(this.tokenStore);
            return tokenServices;
        }
        @Override
        public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
            oauthServer.realm("test/client");
        }
    }

    protected static class Approvals {

        @Autowired
        private ClientDetailsService clientDetailsService;

        @Autowired
        private TokenStore tokenStore;

        @Bean
        public ApprovalStore approvalStore() throws Exception {
            TokenApprovalStore store = new TokenApprovalStore();
            store.setTokenStore(tokenStore);
            return store;
        }

        @Bean
        @Lazy
        @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
        public CustomUserApprovalHandler userApprovalHandler() throws Exception {
            CustomUserApprovalHandler handler = new CustomUserApprovalHandler();
            handler.setApprovalStore(approvalStore());
            handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
            handler.setClientDetailsService(clientDetailsService);
            handler.setUseApprovalStore(true);
            return handler;
        }
    }
}

创建WebSecurity配置适配器的另一个实例。如果URL不是以/api/开头,则将使用此配置。此配置在ApiWebSecurityConfigurationAdapter之后考虑,因为它的@Order值在1之后(没有@Order默认为last)

您应该在
ResourceServerConfigurerAdapter
http块中指定
antMatcher

@Override
public void configure(HttpSecurity http) throws Exception {
    http.sessionManagement().
            sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http.antMatcher("/api/**").authorizeRequests()
            .antMatchers("/api/register").permitAll()

            ......

            .expressionHandler(webExpressionHandler());
    http.csrf().disable();
    http.exceptionHandling().authenticationEntryPoint(new OAuth2AuthenticationEntryPoint());

}
希望对您有所帮助

请参见

创建WebSecurity配置适配器的另一个实例。如果URL不是以/api/开头,则将使用此配置。此配置在ApiWebSecurityConfigurationAdapter之后考虑,因为它的@Order值在1之后(没有@Order默认为last)

您应该在
ResourceServerConfigurerAdapter
http块中指定
antMatcher

@Override
public void configure(HttpSecurity http) throws Exception {
    http.sessionManagement().
            sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http.antMatcher("/api/**").authorizeRequests()
            .antMatchers("/api/register").permitAll()

            ......

            .expressionHandler(webExpressionHandler());
    http.csrf().disable();
    http.exceptionHandling().authenticationEntryPoint(new OAuth2AuthenticationEntryPoint());

}
希望能有帮助