Spring security with Oauth2 or Http-Basic authentication for the same resource

前端 未结 8 1189
南方客
南方客 2021-01-30 09:07

I\'m attempting to implement an API with resources that are protected by either Oauth2 OR Http-Basic authentication.

When I load the WebSecurityConfigurerAdapter which a

8条回答
  •  终归单人心
    2021-01-30 09:39

    You can add a BasicAuthenticationFilter to the security filter chain to get OAuth2 OR Basic authentication security on a protected resource. Example config is below...

    @Configuration
    @EnableResourceServer
    public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
    
        @Autowired
        private AuthenticationManager authenticationManagerBean;
    
        @Override
        public void configure(HttpSecurity http) throws Exception {
            // @formatter:off
            final String[] userEndpoints = {
                "/v1/api/airline"
            };
    
            final String[] adminEndpoints = {
                    "/v1/api/jobs**"
                };
    
            http
                .requestMatchers()
                    .antMatchers(userEndpoints)
                    .antMatchers(adminEndpoints)
                    .antMatchers("/secure/**")
                    .and()
                .authorizeRequests()
                    .antMatchers("/secure/**").authenticated()
                    .antMatchers(userEndpoints).hasRole("USER")
                    .antMatchers(adminEndpoints).hasRole("ADMIN");
    
            // @formatter:on
            http.addFilterBefore(new BasicAuthenticationFilter(authenticationManagerBean),
                    UsernamePasswordAuthenticationFilter.class);
        }
    
    }
    

提交回复
热议问题