Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
694 views
in Technique[技术] by (71.8m points)

spring-boot - Spring Security对不同的URL使用不同的WebSecurityConfigurerAdapters(Spring security use different WebSecurityConfigurerAdapters for different urls)

I need to use two authentication way for different paths in spring security.

(我需要在弹簧安全性的不同路径中使用两种身份验证方式。)

For example , I want use UserDetailService (provided default by spring) authentication for /panel/** and I want to use custom authentication provider that connect third-party service for /member/** .

(例如,我想对/panel/**使用UserDetailService(春季默认提供)身份验证,并且我想对/member/**使用连接第三方服务的定制身份验证提供程序。)

But I only can use one of authentication providers at the same time.

(但是我只能同时使用身份验证提供程序之一。)

How to use them separately by path uri

(如何通过路径uri分别使用它们)

First authentication config

(首次身份验证配置)

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(1)
public class ApiSecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    @Qualifier("panelUserDetailsService")
    private PinpongPanelUserDetailService panelUserDetailsService;

    @Autowired
    private JwtRequestFilter jwtRequestFilter;

    public ApiSecurityConfig(PinpongPanelUserDetailService panelUserDetailService, JwtRequestFilter jwtRequestFilter){
        this.panelUserDetailsService = panelUserDetailService;
        this.jwtRequestFilter = jwtRequestFilter;

    }

    @Autowired
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        // configure AuthenticationManager so that it knows from where to load
        // user for matching credentials
        // Use BCryptPasswordEncoder
        auth.userDetailsService(panelUserDetailsService).passwordEncoder(passwordEncoder());

    }

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

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

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        // We don't need CSRF for this example
        httpSecurity.csrf().disable().
                // dont authenticate this particular request
                authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/panel/authenticate").permitAll()
                .antMatchers("/panel/**").hasRole(PredifinedRole.PANEL_USER.getRole())
                .anyRequest().authenticated()

                // all other requests need to be authenticate
                .and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // Add a filter to validate the tokens with every request
        httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
        httpSecurity
                .exceptionHandling()
                .authenticationEntryPoint((request, response, e) ->
                {
                    response.setContentType("application/json;charset=UTF-8");
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                    response.getWriter().write(new  JSONObject()
                            .put("timestamp", LocalDateTime.now())
                            .put("message", "Access denied")
                            .toString());
                });
    }



}

Second Authentication config

(第二身份验证配置)

@Configuration
@EnableWebSecurity
@Order(2)
public class MobileClientSecurityConfig extends WebSecurityConfigurerAdapter {

    //My custom authentication provider that connect third-party service
    @Autowired
    private UniversityMemberAuthenticationProvider authProvider;

    @Autowired
    private MobileRequestFilter mobileRequestFilter;


    @Autowired
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authProvider);
    }



    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        // We don't need CSRF for this example
        httpSecurity.csrf().disable().
                // dont authenticate this particular request
                        authorizeRequests()
                .antMatchers("/member/authenticate").permitAll()
                .antMatchers("/member/**").hasRole(PredifinedRole.UNIVERSITY_MEMBER.getRole())
                .anyRequest().permitAll()

                // all other requests need to be authenticate
                .and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // Add a filter to validate the tokens with every request
        httpSecurity.addFilterBefore(mobileRequestFilter, UsernamePasswordAuthenticationFilter.class);
        httpSecurity
                .exceptionHandling()
                .authenticationEntryPoint((request, response, e) ->
                {
                    response.setContentType("application/json;charset=UTF-8");
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                    response.getWriter().write(new JSONObject()
                            .put("timestamp", LocalDateTime.now())
                            .put("message", "Access denied")
                            .toString());
                });
    }
}
  ask by yunus kula translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...