0
votes

I added spring security filter to my MVC project with java config. The project have a /home method which only allow authenticated user to access.

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/home").authenticated()
    .and().formLogin()
    .and().httpBasic(); 
}

which is working as expected, when I request "http://localhost:8080/project/home" it kicks my out to "/login". After successful login, I can now view "/home"

then I add OAuth2, pretty much same setting as Sparklr2 example

@Configuration
public class OAuthServerConfig {
private static final String RESOURCE_ID = "cpe";



@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID).stateless(false);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            // Since we want the protected resources to be accessible in the UI as well we need 
            // session creation to be allowed (it's disabled by default in 2.0.6)
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
        .and()
            .requestMatchers().antMatchers("/device/**", "/oauth/users/**", "/oauth/clients/**","/me")
        .and()
            .authorizeRequests()
                .antMatchers("/me").access("#oauth2.hasScope('read')")                  
                .antMatchers("/device").access("#oauth2.hasScope('read') or (!#oauth2.isOAuth() and hasRole('ROLE_USER'))")                                        
                //.antMatchers("/device/trusted/**").access("#oauth2.hasScope('trust')")
                .antMatchers("/device/user/**").access("#oauth2.hasScope('trust')")                 
                .antMatchers("/device/**").access("#oauth2.hasScope('read') or (!#oauth2.isOAuth() and hasRole('ROLE_USER'))")
                .antMatchers("/device/register").access("#oauth2.hasScope('write') or (!#oauth2.isOAuth() and hasRole('ROLE_USER'))")
                .regexMatchers(HttpMethod.DELETE, "/oauth/users/([^/].*?)/tokens/.*")
                    .access("#oauth2.clientHasRole('ROLE_CLIENT') and (hasRole('ROLE_USER') or #oauth2.isClient()) and #oauth2.hasScope('write')")
                .regexMatchers(HttpMethod.GET, "/oauth/clients/([^/].*?)/users/.*")
                    .access("#oauth2.clientHasRole('ROLE_CLIENT') and (hasRole('ROLE_USER') or #oauth2.isClient()) and #oauth2.hasScope('read')")
                .regexMatchers(HttpMethod.GET, "/oauth/clients/.*")
                    .access("#oauth2.clientHasRole('ROLE_CLIENT') and #oauth2.isClient() and #oauth2.hasScope('read')");
        // @formatter:on
    }

}

@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private DataSource dataSource;      
    @Autowired
    private TokenStore tokenStore;
    @Autowired
    private UserApprovalHandler userApprovalHandler;

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

    //needs to be change
    @Value("${tonr.redirect:http://localhost:8080/tonr2/sparklr/redirect}")
    private String tonrRedirectUri;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        //JdbcClientDetailsServiceBuilder           
        clients.jdbc(dataSource);           
    }

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

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

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.realm("dragonfly/client");
    }

}

protected static class Stuff {

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    private TokenStore tokenStore;

    @Bean
    public ApprovalStore approvalStore() throws Exception {
        TokenApprovalStore store = new TokenApprovalStore();
        store.setTokenStore(tokenStore);
        return store;
    }

    @Bean
    @Lazy
    @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
    public DragonflyUserApprovalHandler userApprovalHandler() throws Exception {
        DragonflyUserApprovalHandler handler = new DragonflyUserApprovalHandler();
        handler.setApprovalStore(approvalStore());
        handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
        handler.setClientDetailsService(clientDetailsService);
        handler.setUseApprovalStore(true);
        return handler;
    }
}

}

with only 1 client detail

client.dataSource(dataSource)
    .withClient("my-trusted-client-with-secret")
     .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
     .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
     .scopes("read", "write", "trust")
     .secret("somesecret");

I run this on my tomcat server, the OAuth works, I make request to /oauth/token, it successfully returns token to me.

I restart my application, then request /home without login, it shows up my home view with full content, without login, I couldn't understand. here is the server log when I request /home

it try to match OAuth filter first, which has Order 0. no match found. then check session, no session found, create a new one. then it says it is not OAuth request and no token found. and it continues down the filter chain, AnonymousAuthenticationFilter, then granted ROLE_ANONYMOUS, by that it response to the request with successful. which is the opposite to my rule .antMatchers("/home").authenticated()

How does that happen?

14:40:51.843 [http-nio-8080-exec-6] DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/oauth/token'] 14:40:51.843 [http-nio-8080-exec-6] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/home'; against '/oauth/token' 14:40:51.843 [http-nio-8080-exec-6] DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/oauth/token_key'] 14:40:51.843 [http-nio-8080-exec-6] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/home'; against '/oauth/token_key' 14:40:51.843 [http-nio-8080-exec-6] DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/oauth/check_token'] 14:40:51.843 [http-nio-8080-exec-6] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/home'; against '/oauth/check_token' 14:40:51.843 [http-nio-8080-exec-6] DEBUG o.s.s.w.u.matcher.OrRequestMatcher - No matches found 14:40:51.843 [http-nio-8080-exec-6] DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfiguration$NotOAuthRequestMatcher@7926d3d3 14:40:51.843 [http-nio-8080-exec-6] DEBUG o.s.s.w.u.matcher.OrRequestMatcher - matched 14:40:51.843 [http-nio-8080-exec-6] DEBUG o.s.security.web.FilterChainProxy - /home at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter' 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.security.web.FilterChainProxy - /home at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter' 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - No HttpSession currently exists 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: null. A new one will be created. 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.security.web.FilterChainProxy - /home at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter' 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.s.w.h.writers.HstsHeaderWriter - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@3d823ea7 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.security.web.FilterChainProxy - /home at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter' 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/home'; against '/logout' 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.security.web.FilterChainProxy - /home at position 5 of 11 in additional filter chain; firing Filter: 'OAuth2AuthenticationProcessingFilter' 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.s.o.p.a.BearerTokenExtractor - Token not found in headers. Trying request parameters. 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.s.o.p.a.BearerTokenExtractor - Token not found in request parameters. Not an OAuth2 request. 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.s.o.p.a.OAuth2AuthenticationProcessingFilter - No token in request, will continue chain. 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.security.web.FilterChainProxy - /home at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter' 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.security.web.FilterChainProxy - /home at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter' 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.security.web.FilterChainProxy - /home at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter' 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.s.w.a.AnonymousAuthenticationFilter - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS' 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.security.web.FilterChainProxy - /home at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter' 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.security.web.FilterChainProxy - /home at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter' 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.security.web.FilterChainProxy - /home at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor' 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/home'; against '/me' 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/home'; against '/device' 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/home'; against '/device/user/' 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/home'; against '/device/' 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/home'; against '/device/register' 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.s.w.u.m.RegexRequestMatcher - Checking match of request : '/home'; against '/oauth/clients/([^/].?)/users/.' 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.s.w.u.m.RegexRequestMatcher - Checking match of request : '/home'; against '/oauth/clients/.' 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Public object - authentication not attempted 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.security.web.FilterChainProxy - /home reached end of additional filter chain; proceeding with original chain 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.web.servlet.DispatcherServlet - DispatcherServlet with name 'dispatcher' processing GET request for [/Dragonfly/home] 14:40:51.844 [http-nio-8080-exec-6] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Looking up handler method for path /home 14:40:51.845 [http-nio-8080-exec-6] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Returning handler method [public java.lang.String com.umedia.Dragonfly.controller.HomeController.home()] 14:40:51.845 [http-nio-8080-exec-6] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'homeController' 14:40:51.845 [http-nio-8080-exec-6] DEBUG o.s.web.servlet.DispatcherServlet - Last-Modified value for [/Dragonfly/home] is: -1 14:40:51.845 [http-nio-8080-exec-6] DEBUG o.s.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.JstlView: name 'home'; URL [/WEB-INF/views/home.jsp]] in DispatcherServlet with name 'dispatcher' 14:40:51.845 [http-nio-8080-exec-6] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'requestDataValueProcessor' 14:40:51.845 [http-nio-8080-exec-6] DEBUG o.s.web.servlet.view.JstlView - Forwarding to resource [/WEB-INF/views/home.jsp] in InternalResourceView 'home' 14:40:51.847 [http-nio-8080-exec-6] DEBUG o.s.web.servlet.DispatcherServlet - Successfully completed request 14:40:51.847 [http-nio-8080-exec-6] DEBUG o.s.s.w.a.ExceptionTranslationFilter - Chain processed normally 14:40:51.847 [http-nio-8080-exec-6] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession. 14:40:51.847 [http-nio-8080-exec-6] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/oauth/token'] 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/resources/05.jpg'; against '/oauth/token' 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/oauth/token_key'] 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/resources/05.jpg'; against '/oauth/token_key' 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/oauth/check_token'] 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/resources/05.jpg'; against '/oauth/check_token' 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.w.u.matcher.OrRequestMatcher - No matches found 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfiguration$NotOAuthRequestMatcher@7926d3d3 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.w.u.matcher.OrRequestMatcher - matched 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.security.web.FilterChainProxy - /resources/05.jpg at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter' 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.security.web.FilterChainProxy - /resources/05.jpg at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter' 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - HttpSession returned null object for SPRING_SECURITY_CONTEXT 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@ba8ab6a. A new one will be created. 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.security.web.FilterChainProxy - /resources/05.jpg at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter' 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.w.h.writers.HstsHeaderWriter - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@3d823ea7 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.security.web.FilterChainProxy - /resources/05.jpg at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter' 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/resources/05.jpg'; against '/logout' 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.security.web.FilterChainProxy - /resources/05.jpg at position 5 of 11 in additional filter chain; firing Filter: 'OAuth2AuthenticationProcessingFilter' 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.o.p.a.BearerTokenExtractor - Token not found in headers. Trying request parameters. 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.o.p.a.BearerTokenExtractor - Token not found in request parameters. Not an OAuth2 request. 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.o.p.a.OAuth2AuthenticationProcessingFilter - No token in request, will continue chain. 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.security.web.FilterChainProxy - /resources/05.jpg at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter' 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.security.web.FilterChainProxy - /resources/05.jpg at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter' 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.security.web.FilterChainProxy - /resources/05.jpg at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter' 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.w.a.AnonymousAuthenticationFilter - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@6faeba70: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffbcba8: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 737F9CEEE6747FABCB433614EF76CF3B; Granted Authorities: ROLE_ANONYMOUS' 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.security.web.FilterChainProxy - /resources/05.jpg at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter' 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.security.web.FilterChainProxy - /resources/05.jpg at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter' 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.security.web.FilterChainProxy - /resources/05.jpg at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor' 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/resources/05.jpg'; against '/me' 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/resources/05.jpg'; against '/device' 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/resources/05.jpg'; against '/device/user/' 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/resources/05.jpg'; against '/device/' 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/resources/05.jpg'; against '/device/register' 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.w.u.m.RegexRequestMatcher - Checking match of request : '/resources/05.jpg'; against '/oauth/clients/([^/].?)/users/.' 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.w.u.m.RegexRequestMatcher - Checking match of request : '/resources/05.jpg'; against '/oauth/clients/.' 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Public object - authentication not attempted 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.security.web.FilterChainProxy - /resources/05.jpg reached end of additional filter chain; proceeding with original chain 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.web.servlet.DispatcherServlet - DispatcherServlet with name 'dispatcher' processing GET request for [/Dragonfly/resources/05.jpg] 14:40:51.865 [http-nio-8080-exec-7] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Looking up handler method for path /resources/05.jpg 14:40:51.866 [http-nio-8080-exec-7] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Did not find handler method for [/resources/05.jpg] 14:40:51.866 [http-nio-8080-exec-7] DEBUG o.s.s.o.p.e.FrameworkEndpointHandlerMapping - Looking up handler method for path /resources/05.jpg 14:40:51.866 [http-nio-8080-exec-7] DEBUG o.s.s.o.p.e.FrameworkEndpointHandlerMapping - Did not find handler method for [/resources/05.jpg] 14:40:51.866 [http-nio-8080-exec-7] DEBUG o.s.w.s.h.SimpleUrlHandlerMapping - Matching patterns for request [/resources/05.jpg] are [/resources/**] 14:40:51.866 [http-nio-8080-exec-7] DEBUG o.s.w.s.h.SimpleUrlHandlerMapping - URI Template variables for request [/resources/05.jpg] are {} 14:40:51.866 [http-nio-8080-exec-7] DEBUG o.s.w.s.h.SimpleUrlHandlerMapping - Mapping [/resources/05.jpg] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[ServletContext resource [/resources/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@20458412]]] and 1 interceptor 14:40:51.866 [http-nio-8080-exec-7] DEBUG o.s.web.servlet.DispatcherServlet - Last-Modified value for [/Dragonfly/resources/05.jpg] is: -1 14:40:51.867 [http-nio-8080-exec-7] DEBUG o.s.web.servlet.DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'dispatcher': assuming HandlerAdapter completed request handling 14:40:51.867 [http-nio-8080-exec-7] DEBUG o.s.web.servlet.DispatcherServlet - Successfully completed request 14:40:51.867 [http-nio-8080-exec-7] DEBUG o.s.s.w.a.ExceptionTranslationFilter - Chain processed normally 14:40:51.867 [http-nio-8080-exec-7] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession. 14:40:51.867 [http-nio-8080-exec-7] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed

1
I have log which stackoverflow doesn't allow me to post, it says it looks like spam.Maxi Wu
You have multiple HttpSecurity configuration, use @Order(1) in your security configuration class which filter the /home. See my answer here stackoverflow.com/questions/32206843/…KSTN
you are right, that is exactly the problem. I know that OAuth2 is using Order(0), but I did not know I have to specify Order(1) to work with it. thank you so much.Maxi Wu
after testing my oauth resources, adding Order(1) to my security will break my oauth resources protection. that is, all my security setting in ResourceServerConfiguration is skipped. my oauth resource are now accessible without any authentication and authorization. maybe something else needs to be done to work with this Order(1)?Maxi Wu
your order value should be above 3, this is because OAuth has order=3. Try to annotate it with Order(4)KSTN

1 Answers

1
votes

it looks like you have problems with your project setup and pom configuration

  1. You added spring boot dependencies, yet you don't use spring boot.
  2. Your project is package as jar, yet you you have WEB-INF and use WebApplicationInitializer rather than spring boot
  3. Your pom dependencies is wrong

I have modified several things:

  1. move WebContent folder and rename it to src/main/webapp
  2. update your pom configuration

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    
    <groupId>com.umedia</groupId>
    <artifactId>Dragonfly</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    
    <name>Dragonfly</name>
    <url>http://maven.apache.org</url>
    
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.4.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.4.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.4-1201-jdbc41</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
            <version>2.0.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            <version>1.1.7</version>
        </dependency>
    
    </dependencies>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.0</version>
                <configuration>
                    <path>/</path>
                </configuration>
            </plugin>
        </plugins>
        <finalName>liveBLE</finalName>
    </build>
    </project>
    

run it using mvn tomcat7:run. If I access /home I will be redirected to login page and if I access /device i will get

<oauth>
<error_description>
Full authentication is required to access this resource
</error_description>
<error>unauthorized</error>
</oauth>

This is the expected behavior using OAuth and Spring security.