2

I am using Oauth2 with spring boot 1.5.2.RELEASE. When I am trying to override the configure method of the ResourceServerConfigurerAdapter class it gives me a compilation error. But this is working fine with Spring boot 1.2.6.RELEASE.

Below is my code,

@Override
public void configure(HttpSecurity http) throws Exception {
    http
        .exceptionHandling()
        .authenticationEntryPoint(customAuthenticationEntryPoint)
        .and()
        .logout()
        .logoutUrl("/oauth/logout")
        .logoutSuccessHandler(customLogoutSuccessHandler)
        .and()
        .csrf()
        .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
        .disable()
        .headers()
        .frameOptions().disable()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .authorizeRequests()
        .antMatchers("/hello/").permitAll()
        .antMatchers("/secure/**").authenticated();
}

Above code is working fine in the Spring Boot 1.2.6 but there is a compilation error when I try to call sessionManagement() method in 1.5.2 version. I guess the method has been removed in the new version.

But when I try with disable().and().sessionManagement() the compilation error removes but authentication is not working as expected. Can anybody help me to resolve this.

Below is my full code

@Configuration
public class OAuth2Configuration {

    @Configuration
    @EnableResourceServer
    @ComponentScan(basePackages = "security")
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        @Autowired
        private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;

        @Autowired
        private CustomLogoutSuccessHandler customLogoutSuccessHandler;

        @Override
        public void configure(HttpSecurity http) throws Exception {

            http
                .exceptionHandling()
                .authenticationEntryPoint(customAuthenticationEntryPoint)
                .and()
                .logout()
                .logoutUrl("/oauth/logout")
                .logoutSuccessHandler(customLogoutSuccessHandler)
                .and()
                .csrf()
                .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
                .disable()
                .headers()
                .frameOptions().disable().and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/hello/").permitAll()
                .antMatchers("/secure/**").authenticated();

        }

    }

    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter implements EnvironmentAware {

        private static final String ENV_OAUTH = "authentication.oauth.";
        private static final String PROP_CLIENTID = "clientid";
        private static final String PROP_SECRET = "secret";
        private static final String PROP_TOKEN_VALIDITY_SECONDS = "tokenValidityInSeconds";

        private RelaxedPropertyResolver propertyResolver;

        @Autowired
        private DataSource dataSource;

        @Bean
        public TokenStore tokenStore() {
            return new JdbcTokenStore(dataSource);
        }

        @Autowired
        @Qualifier("authenticationManagerBean")
        private AuthenticationManager authenticationManager;

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints)
            throws Exception {
            endpoints
                .tokenStore(tokenStore())
                .authenticationManager(authenticationManager);
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients
                .inMemory()
                .withClient(propertyResolver.getProperty(PROP_CLIENTID))
                .scopes("read", "write")
                .authorities(Authorities.ROLE_ADMIN.name(), Authorities.ROLE_USER.name())
                .authorizedGrantTypes("password", "refresh_token")
                .secret(propertyResolver.getProperty(PROP_SECRET))
                .accessTokenValiditySeconds(propertyResolver.getProperty(PROP_TOKEN_VALIDITY_SECONDS, Integer.class, 1800));
        }


        public void setEnvironment(Environment environment) {
            this.propertyResolver = new RelaxedPropertyResolver(environment, ENV_OAUTH);
        }

    }

}

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

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

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        auth
            .userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder());

    }

    @Override
    public void configure(WebSecurity web) throws Exception {

        web
            .ignoring()
            .antMatchers("/h2console/**")
            .antMatchers("/api/register")
            .antMatchers("/api/activate")
            .antMatchers("/api/lostpassword")
            .antMatchers("/api/resetpassword")
            .antMatchers("/api/hello");

    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
    private static class GlobalSecurityConfiguration extends GlobalMethodSecurityConfiguration {
        @Override
        protected MethodSecurityExpressionHandler createExpressionHandler() {
            return new OAuth2MethodSecurityExpressionHandler();
        }

    }

}

@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private final Logger log = LoggerFactory.getLogger(CustomAuthenticationEntryPoint.class);

    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException ae) throws IOException, ServletException {

        log.info("Pre-authenticated entry point called. Rejecting access");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access Denied");

    }
}
Kepler
  • 399
  • 1
  • 7
  • 19
  • Possible duplicate of [OAuth2 with Spring Boot REST application - cannot access resource with token](http://stackoverflow.com/questions/42320756/oauth2-with-spring-boot-rest-application-cannot-access-resource-with-token) – Tom Mar 08 '17 at 07:58
  • 1
    @Tom No. This is not the duplication of that question. Please have a closer look. This is completely different. – Kepler Mar 08 '17 at 11:07
  • 1
    Filtering order is not the problem here. The problem is they have changed the api of WebSecurityConfigurerAdapter. My question is on changing my configure method implementation related to the api change ? Please don't try to make useless comments just looking at the surface of a question. Just have a closer look at a question before making a judgement. – Kepler Mar 08 '17 at 11:50
  • Got the same problem, my code works fine with 1.4.2, but not working properly with 1.5.2. do you find any solution? – Cryse Hillmes Mar 10 '17 at 15:39

2 Answers2

11

According to Spring Boot 1.5 Release Notes:

OAuth 2 Resource Filter

The default order of the OAuth2 resource filter has changed from 3 to SecurityProperties.ACCESS_OVERRIDE_ORDER - 1. This places it after the actuator endpoints but before the basic authentication filter chain. The default can be restored by setting security.oauth2.resource.filter-order = 3

So just add security.oauth2.resource.filter-order = 3 to your application.properties would solve this problem.

Community
  • 1
  • 1
Cryse Hillmes
  • 196
  • 1
  • 3
2

Yes. The API is bit changed. sessionManagement method can be invoked with a reference of HttpSecurity.

http
    .exceptionHandling()
    .authenticationEntryPoint(customAuthenticationEntryPoint)
    .and()
    .logout()
    .logoutUrl("/oauth/logout")
    .logoutSuccessHandler(customLogoutSuccessHandler)
    .and()
    .csrf()
    .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
    .disable()
    .headers()
    .frameOptions().disable();

http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .and()
    .authorizeRequests()
    .antMatchers("/hello/").permitAll()
    .antMatchers("/secure/**").authenticated();

However you haven't provided enough information to resolve your authentication issue. An answer given to the following problem can be able to resolve your problem.

Spring boot Oauth 2 configuration cause to 401 even with the permitall antMatchers

Dilan
  • 1,389
  • 5
  • 14
  • 24