首页 > 解决方案 > Spring security java配置和多个http入口点

问题描述

^_^

我正在使用 Spring 安全性来保护 RESTFull API 和 Web 应用程序,同时问题是当我发送 Rest 请求时,我收到 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 的配置单独运行良好,并且对于 Web 应用程序配置相同,但是当我希望它们都像上述配置一样运行时,只有其中一个运行具有 Order(1)

请帮忙 !!!谢谢你。

标签: spring-security

解决方案


大家好!!!!

刚刚解决了问题

这是正确的配置^_^ 

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

非常感谢你们,祝大家好运^_^ 


推荐阅读