Sunil Chauraha
Sunil Chauraha

Reputation: 555

Disabling authentication in “OAUTH2” enabled boot application

How to disable authentication in “OAUTH2” enabled spring-boot application? This is often required for testing or during build phase.

Upvotes: 5

Views: 8357

Answers (1)

Sunil Chauraha
Sunil Chauraha

Reputation: 555

This is a valid scenario when we want to do the testing/build and we don’t have OAuth2 token available on the fly. Below are the steps to be followed:

  1. Create a YAML file without OAuth2 configuration (i.e. application-{profile_name}.yml) and add below properties in it:

    Security.ignored = /** 
    security.basic.enable=false
    
  2. Add a class which is bypassing HTTP/S requests authorization. Note: This class should have same profile name (i.e. {profile_name}).

    @Profile({"profile_name"})
    public class DisableOAuth2Config {
    
        @Bean
        public ResourceServerConfigurer resourceServerConfigurer() {
            return new ResourceServerConfigurerAdapter() {
                @Override
                public void configure(HttpSecurity http) throws Exception {
                    http
                        .authorizeRequests()
                            .antMatchers("/**").permitAll();
                }
            };
        }
    }
    
  3. Provide Profile in SecurityConfiguration class where we still want to have security. @Profile({"local","dev","aws"}), This will differentiate profiles for both enabled/disabled security.

  4. Note: Please check annotations @EnableResourceServe, @EnableWebSecurity and @EnableGlobalMethodSecurity(prePostEnabled = true). They should be available only in SecurityConfiguration class. Not multiple places and not in SpringBoot class.

Upvotes: 3

Related Questions