0
votes

spring boot oauth2 ResourceServerConfigurerAdapter not protecting resourcs

/oauth/token working fine.

.antMatchers("/api/waiter/**") in resourceserver is accessible by public.

.antMatchers("/api/waiter/").hasAnyRole(RESTRWAITER).antMatchers("/api/waiter/").authenticated()

i have clearly defined role for api.

seem like problem in resource server configuration.

My Codes Are

@Configuration
@EnableResourceServer
@Order(2)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

@Value("${spring.datasource.driver-class-name}")
private String oauthClass;

@Value("${spring.datasource.url}")
private String oauthUrl;

@Value("${spring.datasource.username}")
private String username;

@Value("${spring.datasource.password}")
private String password;

private static final String RESTRWAITER = "WAITER";

@Bean
public TokenStore tokenStore() {
    DataSource tokenDataSource = DataSourceBuilder.create().driverClassName(oauthClass).username(username)
            .password(password).url(oauthUrl).build();
    return new JdbcTokenStore(tokenDataSource);
}

@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
    resources.resourceId("scout").tokenStore(tokenStore());
}

@Override
public void configure(HttpSecurity http) throws Exception {
    http.anonymous().disable().requestMatchers().antMatchers("/api/waiter/**").and().authorizeRequests()
            .antMatchers("/api/waiter/**").hasAnyRole(RESTRWAITER).antMatchers("/api/waiter/**").authenticated().and().exceptionHandling()
            .accessDeniedHandler(new OAuth2AccessDeniedHandler());

}

}

And

AuthorizationServerConfig

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

@Autowired
private AuthenticationManager authenticationManager;

@Value("${spring.datasource.driver-class-name}")
private String oauthClass;

@Value("${spring.datasource.url}")
private String oauthUrl;

@Value("${spring.datasource.username}")
private String username;

@Value("${spring.datasource.password}")
private String password;

@Bean
public TokenStore tokenStore() {
    System.out.println(username);
    DataSource tokenDataSource = DataSourceBuilder.create().driverClassName(oauthClass).username(username)
            .password(password).url(oauthUrl).build();
    return new JdbcTokenStore(tokenDataSource);
}

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

@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()")
            .allowFormAuthenticationForClients();
}

@Bean
public PasswordEncoder getPasswordEncoder() {
    return new BCryptPasswordEncoder();
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.inMemory().withClient("clientapp").secret(getPasswordEncoder().encode("123456"))
            .authorizedGrantTypes("password", "authorization_code", "refresh_token").authorities("READ_ONLY_CLIENT")
            .scopes("read_profile_info").resourceIds("oauth2-resource").redirectUris("http://localhost:8081/login")
            .accessTokenValiditySeconds(120000).refreshTokenValiditySeconds(240000);
}

}

and

SecurityConfiguration

@Configuration
@EnableWebSecurity
@Order(1)
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, proxyTargetClass = true)
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

private static final String SYSTEM = "SYSTEM";
private static final String RESTRUSER = "RESTRO";
private static final String RESTRWAITER = "WAITER";

@Autowired
private UserDetailsService userDetailsService;

@Autowired
private DataSource dataSource;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(getPasswordEncoder());

}

@Bean
public AuthenticationFailureHandler customAuthenticationFailureHandler() {
    return new CustomAuthenticationFailureHandler();
}

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

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

        web
            .ignoring()
            .antMatchers("/api/waiter/**");

    }

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/admin/**").hasRole(SYSTEM).antMatchers("/restro/**")
            .hasAnyRole(RESTRUSER).antMatchers("/waiter/**").hasAnyRole(RESTRWAITER).antMatchers("/", "/pub/**")
            .permitAll().and().formLogin().loginPage("/login").defaultSuccessUrl("/dashboard")
            .failureHandler(customAuthenticationFailureHandler()).permitAll().and().logout()
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/?logout")
            .deleteCookies("my-remember-me-cookie").permitAll().and().rememberMe()
            // .key("my-secure-key")
            .rememberMeCookieName("my-remember-me-cookie").tokenRepository(persistentTokenRepository())
            .tokenValiditySeconds(24 * 60 * 60).and().exceptionHandling();
}

PersistentTokenRepository persistentTokenRepository() {
    JdbcTokenRepositoryImpl tokenRepositoryImpl = new JdbcTokenRepositoryImpl();
    tokenRepositoryImpl.setDataSource(dataSource);
    return tokenRepositoryImpl;
}

@Bean
public PasswordEncoder getPasswordEncoder() {
    return new BCryptPasswordEncoder();
}

}

The problem is resource server .antMatchers("/api/waiter/**") is accessible without access_token. Resource server configuration not working.

1

1 Answers

0
votes

Got found solution

just replaced @Order(1) with @Order(SecurityProperties.BASIC_AUTH_ORDER) on SecurityConfiguration . And its worked.

@Configuration
@EnableWebSecurity
@Order(SecurityProperties.BASIC_AUTH_ORDER)
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, proxyTargetClass = true)
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {