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

前端 未结 8 1153
南方客
南方客 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);
        }
    
    }
    
    0 讨论(0)
  • 2021-01-30 09:45

    I believe that is not possible to have both authentications. You can have basic authentication and oauth2 authentication, but for distinct endpoints. The way as you did, the first configuration will overcome the second, in this case, http basic will be used.

    0 讨论(0)
提交回复
热议问题