簡體   English   中英

Oauth2資源服務器與Spring Security配置重疊

[英]Oauth2 Resource server overlap Spring Security configuration

我正在嘗試在java config上配置Spring Security和OAuth2。 我正在使用Spring Security版本4.0.4.RELEASE和OAuth2版本2.0.11.RELEASE。

Spring Security配置運行良好。 另外,我可以使用OAuth2 AuthorizationServer獲取訪問令牌,但是我的ResourceServer無法正常工作。 設置注釋@EnableResourceServer時,我只能檢查我的訪問令牌和其他無法打開的URL(安全配置和AuthorizationServer配置不起作用)。 我看到以下錯誤:

<oauth>
  <error_description>
     An Authentication object was not found in the SecurityContext
  </error_description>
  <error>unauthorized</error>
</oauth>

如果刪除注釋@EnableResourceServer,則ResourceServer不會檢查訪問令牌。 它只是重定向到身份驗證頁面。

這是我的代碼:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
public class GlobalSecurityConfig extends GlobalMethodSecurityConfiguration {

    @Bean(name = "passwordEncoder")
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Autowired
    @Qualifier("authUserDetailsService")
    private UserDetailsService userDetailsService;

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

    @Autowired
    @Qualifier("permissionEvaluator")
    private PermissionEvaluator permissionEvaluator;


    @Bean
    public DefaultMethodSecurityExpressionHandler expressionHandler() {
        DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
        handler.setDefaultRolePrefix("");
        handler.setPermissionEvaluator(permissionEvaluator);
        return handler;
    }

    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        return expressionHandler();
    }

}

SecurityConfig:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean(name = "clientAuthenticationEntryPoint")
    public OAuth2AuthenticationEntryPoint oauthAuthenticationEntryPoint() {
        OAuth2AuthenticationEntryPoint entry = new OAuth2AuthenticationEntryPoint();
        entry.setRealmName("myapp/client");
        entry.setTypeName("Basic");
        return entry;
    }

    @Autowired
    @Qualifier("webExpressionHandler")
    private DefaultWebSecurityExpressionHandler expressionHandler;


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

    @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                .antMatchers("/html/**", "/webapi/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .requestMatchers().antMatchers("/admin/**", "/**")
                .and()

                .authorizeRequests()

                .expressionHandler(expressionHandler)

                .antMatchers("/admin/**").access("hasRole('ADMINISTRATOR')")
                .antMatchers("/1/admin/**").access("hasRole('ADMINISTRATOR')")
                .antMatchers("/profile**").authenticated()
                .antMatchers("/oauth/authorize").authenticated()
                .and()
                .formLogin().loginPage("/login")
                .failureUrl("/login?error=1")
                .loginProcessingUrl("/login-attempt")
                .defaultSuccessUrl("/", false)
                .and()
                .sessionManagement()
                .sessionFixation().migrateSession()
                .and()

                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/")

                .and()
                .exceptionHandling()
                .accessDeniedPage("/access-denied")
                .and()
                .csrf();
    }
}

Oauth配置:

@Configuration
public class Oauth {

    @Configuration
    @EnableResourceServer
    public static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        private static final String RESOURCE_ID = "my_oauth_server";

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
            resources.resourceId(RESOURCE_ID);
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                    .anonymous().disable()
                    .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                    .authorizeRequests()

                    .regexMatchers("/api/v0/.*").authenticated()
                    .antMatchers("/**").denyAll()
            ;

        }
    }

    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
        @Autowired
        private AuthenticationManager authenticationManager;

        @Autowired
        private AuthorizationCodeServices verificationCodeService;

        @Autowired
        @Qualifier("clientDetails")
        private ClientDetailsService clientDetailsService;

        @Autowired
        @Qualifier("tokenStore")
        private TokenStore tokenStore;

        @Bean(name = "tokenServices")
        public DefaultTokenServices tokenServices() {
            DefaultTokenServices tokenServices = new DefaultTokenServices();
            tokenServices.setTokenStore(tokenStore);
            tokenServices.setSupportRefreshToken(true);
            tokenServices.setClientDetailsService(clientDetailsService);
            return tokenServices;
        }

        @Bean
        public ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter() throws Exception {
            ClientCredentialsTokenEndpointFilter filter = new ClientCredentialsTokenEndpointFilter();
            filter.setAuthenticationManager(authenticationManager);
            return filter;
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients.withClientDetails(clientDetailsService);
        }

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            endpoints.authenticationManager(authenticationManager);
            endpoints.authorizationCodeServices(verificationCodeService);
            endpoints.tokenServices(tokenServices());
            endpoints.reuseRefreshTokens(true);
        }


        @Override
        public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
            oauthServer.tokenKeyAccess("permitAll()");
            oauthServer.checkTokenAccess("permitAll()");
            oauthServer.realm("myapp/client");
            oauthServer.addTokenEndpointAuthenticationFilter(clientCredentialsTokenEndpointFilter());
            oauthServer.allowFormAuthenticationForClients();
        }
    }
}

因此,ResourceServer配置與其他配置重疊。 我該如何解決? 感謝您的幫助。

我看到您想使用訪問令牌保護某些端點,並使用普通形式的登錄名來保護其他端點。

您是否可以嘗試通過以下方式將ResourceServerConfiguration的適用性限制為僅適用於某些端點: http.requestMatcher(new AntPathRequestMatcher("/api/v0/**"))... SecurityConfig進行相同的操作,但對您要處理的端點進行相同的操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM