Настройка безопасности Spring Java и множественная точка входа http - PullRequest
0 голосов
/ 11 января 2019

^ _ ^

Я работаю над безопасностью Spring, чтобы обеспечить безопасность API RESTFull и веб-приложения, в то время как проблема заключается в том, что когда я отправляю запрос на отдых, я получаю HTML-страницу вместо ответа в формате JSON, это моя конфигурация. меня и проверьте конфигурацию

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import com.example.jjjj.faces.MySimpleUrlAuthenticationSuccessHandler;
import com.example.jjjj.security.jwt.JwtAuthEntryPoint;
import com.example.jjjj.security.services.UserDetailsServiceImpl;

@EnableWebSecurity
public class MultiHttpSecurityConfig {



    @Autowired
    UserDetailsServiceImpl userDetailsService;



    @Bean
    public static AuthenticationSuccessHandler myAuthenticationSuccessHandler(){
        return new MySimpleUrlAuthenticationSuccessHandler();
    }


    @Configuration
    public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

        @Autowired
        private JwtAuthEntryPoint unauthorizedHandler;


        protected void configure(HttpSecurity http) throws Exception {





            http.cors().and().csrf().disable().
            authorizeRequests()
            .antMatchers("/api/auth/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);




//          http
//              .antMatcher("/api/**")                               
//              .authorizeRequests()
//                  .anyRequest().hasRole("ADMIN")
//                  .and()
//              .httpBasic();
        }
    }

    @Configuration  
    @Order(1)                                                        

    public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

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


            http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN");                                      
            http.authorizeRequests().antMatchers("/company/**").hasRole("COMPANY_DATA_ENTRY_AGENT");                                      

            /*
            http.cors().and().csrf().disable().
            authorizeRequests()
            .antMatchers("/api/auth/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
            */

            // require all requests to be authenticated except for the resources
            http.authorizeRequests().antMatchers("/javax.faces.resource/**").permitAll().anyRequest().authenticated();

            //http.authorizeRequests().antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')");




            //http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);


            // login
            http.formLogin().loginPage("/login.xhtml").successHandler(myAuthenticationSuccessHandler()).permitAll().failureUrl("/login.xhtml?error=true");
            // logout
            http.logout().logoutSuccessUrl("/login.xhtml");

            // not needed as JSF 2.2 is implicitly protected against CSRF
            http.csrf().disable();






//          http
//              .authorizeRequests()
//                  .anyRequest().authenticated()
//                  .and()
//              .formLogin();
        }
    }
}

конфигурация API работает хорошо одна и та же для конфигурации веб-приложения, но когда я хочу, чтобы они оба работали хорошо, как указано выше, работает только одна из них, которая имеет Order (1)

Пожалуйста, помогите !!! Спасибо.

1 Ответ

0 голосов
/ 11 января 2019

Здравствуйте, ребята снова !!!!

Только что решил проблему

и это правильная конфигурация ^ _ ^

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

    @Configuration
    @Order
    public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {



        @Autowired
        UserDetailsServiceImpl userDetailsService;


        @Autowired
        private JwtAuthEntryPoint unauthorizedHandler;



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

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

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


        protected void configure(HttpSecurity http) throws Exception {

            http.cors().and().csrf().disable().
            authorizeRequests()
            .antMatchers("/api/auth/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

            // require all requests to be authenticated except for the resources
            http.authorizeRequests().antMatchers("/javax.faces.resource/**").permitAll().anyRequest().authenticated();




        }
    }

    @Configuration  
    @Order(1)                                                        
    public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {



        @Autowired
        UserDetailsServiceImpl userDetailsService;

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

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

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



        @Bean
        public AuthenticationSuccessHandler myAuthenticationSuccessHandler(){
            return new MySimpleUrlAuthenticationSuccessHandler();
        }



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

            // not needed as JSF 2.2 is implicitly protected against CSRF
            http.csrf().disable();

            http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN");                                      
            http.authorizeRequests().antMatchers("/company/**").hasRole("COMPANY_DATA_ENTRY_AGENT");                                      



            //http.authorizeRequests().antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')");
            //http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);


            // login
            http.formLogin().loginPage("/login.xhtml").successHandler(myAuthenticationSuccessHandler()).permitAll().failureUrl("/login.xhtml?error=true");
            // logout
            http.logout().logoutSuccessUrl("/login.xhtml");


        }
    }
}

Решение состоит в том, что эта строка должна быть последней antMatch ^ _ ^

http.authorizeRequests().antMatchers("/javax.faces.resource/**").permitAll().anyRequest().authenticated();

Большое спасибо, ребята Удачи всем ^ _ ^

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