Различная конечная точка авторизации в spring-oauth2 - PullRequest
1 голос
/ 13 марта 2020

У меня ниже конфигурация для двух конечных точек, одна для / клиента, а другая для / admin. Авторизуйтесь через oauth2. Каждый из них имеет свой собственный userdetailsservice. Поскольку сервер авторизации отвечает на запросы, полученные из / oauth / token, по умолчанию, как я могу установить разные конечные точки авторизации для каждой конфигурации?

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MultiSecurityConfig {

    @Configuration
    public static class ClientSecurityConfig extends WebSecurityConfigurerAdapter {

        @Autowired
        private CustomUserDetailsService userDetailsService;

        @Override
        public void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService);
        }

        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/data-sync/**", "/favicon.ico", "/error");
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .requestMatchers()
                    .antMatchers("/client/**");
        }

        @Bean
        @Override
        protected AuthenticationManager authenticationManager() throws Exception {
            return super.authenticationManager();
        }

    }

    @Configuration
    public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter {

        @Autowired
        private CustomAdminUserDetailsService userDetailsService;

        @Override
        public void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService);
        }

        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/favicon.ico", "/error");
        }

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

    @Configuration
    @EnableAuthorizationServer
    public static class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

        @Autowired
        PasswordEncoder passwordEncoder;

        @Autowired
        DataSource dataSource;

        @Value("classpath:schema.sql")
        private Resource schemaScript;

        @Autowired
        private AuthenticationManager authenticationManager;

        @Override
        public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
            oauthServer//
                    .tokenKeyAccess("permitAll()")//
                    .checkTokenAccess("isAuthenticated()");
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients//
                    .jdbc(dataSource)//
                    .withClient("trusted-client")//
                    .secret(passwordEncoder.encode("secret"))//
                    .authorizedGrantTypes("password", "authorization_code", "refresh_token")//
                    .scopes("read");
        }

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            final TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
            tokenEnhancerChain.setTokenEnhancers(Collections.singletonList(tokenEnhancer()));
            endpoints
                    .tokenStore(tokenStore())
                    .tokenEnhancer(tokenEnhancerChain)
            .authenticationManager(authenticationManager);
        }

        @Bean
        @Primary
        public DefaultTokenServices tokenServices() {
            final DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
            defaultTokenServices.setTokenStore(tokenStore());
            defaultTokenServices.setSupportRefreshToken(true);
            return defaultTokenServices;
        }

        @Bean
        public TokenEnhancer tokenEnhancer() {
            return new CustomTokenEnhancer();
        }

        // JDBC token store configuration

        @Bean
        public DataSourceInitializer dataSourceInitializer(final DataSource dataSource) {
            final DataSourceInitializer initializer = new DataSourceInitializer();
            initializer.setDataSource(dataSource);
            initializer.setDatabasePopulator(databasePopulator());
            return initializer;
        }

        private DatabasePopulator databasePopulator() {
            final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
            populator.addScript(schemaScript);
            return populator;
        }

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

    }

    @Configuration
    @EnableResourceServer
    public static class ResourceServerConfig extends ResourceServerConfigurerAdapter {

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
            resources.stateless(true);
        }

        @Bean
        public MethodSecurityExpressionHandler createExpressionHandler() {
            return new OAuth2MethodSecurityExpressionHandler();
        }

    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...