Конфигурация Java безопасности Spring и несколько точек входа http

^ _ ^

Я работаю над безопасностью Spring, чтобы защитить RESTFull API и веб-приложение, в то же время проблема в том, что когда я отправляю запрос на отдых, я получаю 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 работает хорошо сама по себе и такая же для конфигурации веб-приложения, но когда я хочу, чтобы они оба работали хорошо, как приведенная выше конфигурация, работает только один из них, который имеет порядок (1)

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

Стоит ли изучать PHP в 2026-2027 годах?
Стоит ли изучать PHP в 2026-2027 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
1
0
930
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

И снова привет, РЕБЯТА !!!!

Просто решил проблему

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

@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();

Большое вам спасибо, РЕБЯТА УДАЧИ всем ^ _ ^

Другие вопросы по теме