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

前端 未结 8 1157
南方客
南方客 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:26

    The solution @kca2ply provided works very well. I noticed the browser wasn't issuing a challenge so I tweaked the code a little to the following:

    @Configuration
    @Order(2)
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
      @Override
      protected void configure(HttpSecurity http) throws Exception {
    
        // @formatter:off
        http.anonymous().disable()
          .requestMatcher(request -> {
              String auth = request.getHeader(HttpHeaders.AUTHORIZATION);
              return (auth != null && auth.startsWith("Basic"));
          })
          .antMatcher("/**")
          .authorizeRequests().anyRequest().authenticated()
        .and()
          .httpBasic();
        // @formatter:on
      }
    
      @Autowired
      public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
        .withUser("user").password("password").roles("USER");
      }
    }
    

    Using both requestMatcher() and antMatcher() made things work perfectly. Browsers and HTTP clients will now challenge for basic creds first if not provided already. If no credentials are provided, it falls through to OAuth2.

提交回复
热议问题