将OAuth和基本身份验证与WebSecurityConfigurerAdapter结合使用

时间:2020-03-04 15:04:21

标签: java spring-boot spring-security spring-oauth2

我需要解决两种身份验证方式:

  1. 基本的执行器端点
  2. 具有oauth jwt令牌的其余端点

    我们已经完成了oauth身份验证,但是现在我们尝试为执行器使用不同的安全性对其进行扩展。下面的代码显示了我们尝试过的内容。执行器开始使用基本身份验证,但是其余端点的oauth身份验证不起作用。

我们可以在没有oauth令牌的情况下呼叫任何端点。

@Configuration
@RequiredArgsConstructor
public class WebSecurityConfig {

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

    @Order(2)
    @Configuration
    public class DefaultConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsServiceImpl;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .sessionManagement(sessionManagement -> sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeRequests(authorizeRequests -> {
                authorizeRequests.antMatchers("/unsecured**").permitAll().anyRequest().authenticated();
            })
            .csrf(AbstractHttpConfigurer::disable);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .userDetailsService(userDetailsServiceImpl)
            .passwordEncoder(passwordEncoder());
    }

    @Bean(name = "authenticationManager")
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        final AuthenticationManager authenticationManager = super.authenticationManagerBean();
        return authenticationManager;
    }
    }

    @Order(1)
    @Configuration
    public class ActuatorConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole("ADMIN")
            .and().httpBasic();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user")
            .roles("ADMIN")
            .password(passwordEncoder().encode("pass"));
    }
    }
}

0 个答案:

没有答案