Search in sources :

Example 26 with HandlerInterceptor

use of org.springframework.web.servlet.HandlerInterceptor in project spring-boot by spring-projects.

the class AbstractEndpointHandlerMappingTests method securityInterceptorShouldBePresentAfterCorsInterceptorForCorsRequest.

@Test
public void securityInterceptorShouldBePresentAfterCorsInterceptorForCorsRequest() throws Exception {
    HandlerInterceptor securityInterceptor = mock(HandlerInterceptor.class);
    TestActionEndpoint endpoint = new TestActionEndpoint(new TestEndpoint("a"));
    AbstractEndpointHandlerMapping<?> mapping = new TestEndpointHandlerMapping<>(Collections.singletonList(endpoint));
    mapping.setApplicationContext(this.context);
    mapping.setSecurityInterceptor(securityInterceptor);
    mapping.afterPropertiesSet();
    MockHttpServletRequest request = request("POST", "/a");
    request.addHeader("Origin", "http://example.com");
    assertThat(mapping.getHandler(request).getInterceptors().length).isEqualTo(2);
    assertThat(mapping.getHandler(request).getInterceptors()[1]).isEqualTo(securityInterceptor);
}
Also used : HandlerInterceptor(org.springframework.web.servlet.HandlerInterceptor) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Test(org.junit.Test)

Example 27 with HandlerInterceptor

use of org.springframework.web.servlet.HandlerInterceptor in project spring-boot by spring-projects.

the class CloudFoundryActuatorAutoConfiguration method cloudFoundryEndpointHandlerMapping.

@Bean
public CloudFoundryEndpointHandlerMapping cloudFoundryEndpointHandlerMapping(MvcEndpoints mvcEndpoints, RestTemplateBuilder restTemplateBuilder, Environment environment) {
    Set<NamedMvcEndpoint> endpoints = new LinkedHashSet<>(mvcEndpoints.getEndpoints(NamedMvcEndpoint.class));
    HandlerInterceptor securityInterceptor = getSecurityInterceptor(restTemplateBuilder, environment);
    CorsConfiguration corsConfiguration = getCorsConfiguration();
    CloudFoundryEndpointHandlerMapping mapping = new CloudFoundryEndpointHandlerMapping(endpoints, corsConfiguration, securityInterceptor);
    mapping.setPrefix("/cloudfoundryapplication");
    return mapping;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) NamedMvcEndpoint(org.springframework.boot.actuate.endpoint.mvc.NamedMvcEndpoint) CorsConfiguration(org.springframework.web.cors.CorsConfiguration) HandlerInterceptor(org.springframework.web.servlet.HandlerInterceptor) ConditionalOnBean(org.springframework.boot.autoconfigure.condition.ConditionalOnBean) Bean(org.springframework.context.annotation.Bean)

Example 28 with HandlerInterceptor

use of org.springframework.web.servlet.HandlerInterceptor in project canal by alibaba.

the class WebConfig method addInterceptors.

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new HandlerInterceptor() {

        @Override
        public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "*");
            httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, X-Token");
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpServletResponse.setHeader("Access-Control-Max-Age", String.valueOf(3600 * 24));
            if (HttpMethod.OPTIONS.toString().equals(httpServletRequest.getMethod())) {
                httpServletResponse.setStatus(HttpStatus.NO_CONTENT.value());
                return false;
            }
            return true;
        }
    }).addPathPatterns("/api/**");
    registry.addInterceptor(new HandlerInterceptor() {

        @Override
        public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
            String token = httpServletRequest.getHeader("X-Token");
            boolean valid = false;
            if (token != null) {
                User user = UserController.loginUsers.getIfPresent(token);
                if (user != null) {
                    valid = true;
                    httpServletRequest.setAttribute("user", user);
                    httpServletRequest.setAttribute("token", token);
                }
            }
            if (!valid) {
                BaseModel baseModel = BaseModel.getInstance(null);
                baseModel.setCode(50014);
                baseModel.setMessage("Expired token");
                ObjectMapper mapper = new ObjectMapper();
                String json = mapper.writeValueAsString(baseModel);
                try {
                    httpServletResponse.setContentType("application/json;charset=UTF-8");
                    PrintWriter out = httpServletResponse.getWriter();
                    out.print(json);
                } catch (Throwable e) {
                    throw new RuntimeException(e);
                }
                return false;
            }
            return true;
        }
    }).addPathPatterns("/api/**").excludePathPatterns("/api/**/config/server_polling").excludePathPatterns("/api/**/config/instances_polling").excludePathPatterns("/api/**/config/instance_polling/**").excludePathPatterns("/api/**/user/login").excludePathPatterns("/api/**/user/logout").excludePathPatterns("/api/**/user/info");
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) User(com.alibaba.otter.canal.admin.model.User) HandlerInterceptor(org.springframework.web.servlet.HandlerInterceptor) BaseModel(com.alibaba.otter.canal.admin.model.BaseModel) HttpServletResponse(javax.servlet.http.HttpServletResponse) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) PrintWriter(java.io.PrintWriter)

Example 29 with HandlerInterceptor

use of org.springframework.web.servlet.HandlerInterceptor in project spring-framework by spring-projects.

the class WebMvcConfigurationSupportTests method beanNameHandlerMapping.

@Test
public void beanNameHandlerMapping() throws Exception {
    ApplicationContext context = initContext(WebConfig.class);
    BeanNameUrlHandlerMapping handlerMapping = context.getBean(BeanNameUrlHandlerMapping.class);
    assertThat(handlerMapping.getOrder()).isEqualTo(2);
    HttpServletRequest request = new MockHttpServletRequest("GET", "/testController");
    HandlerExecutionChain chain = handlerMapping.getHandler(request);
    assertThat(chain).isNotNull();
    HandlerInterceptor[] interceptors = chain.getInterceptors();
    assertThat(interceptors).isNotNull();
    assertThat(interceptors.length).isEqualTo(3);
    assertThat(interceptors[1].getClass()).isEqualTo(ConversionServiceExposingInterceptor.class);
    assertThat(interceptors[2].getClass()).isEqualTo(ResourceUrlProviderExposingInterceptor.class);
}
Also used : MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) AnnotationConfigWebApplicationContext(org.springframework.web.context.support.AnnotationConfigWebApplicationContext) ApplicationContext(org.springframework.context.ApplicationContext) BeanNameUrlHandlerMapping(org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping) HandlerExecutionChain(org.springframework.web.servlet.HandlerExecutionChain) HandlerInterceptor(org.springframework.web.servlet.HandlerInterceptor) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) Test(org.junit.jupiter.api.Test)

Example 30 with HandlerInterceptor

use of org.springframework.web.servlet.HandlerInterceptor in project spring-framework by spring-projects.

the class WebMvcConfigurationSupportTests method requestMappingHandlerMapping.

@Test
public void requestMappingHandlerMapping() throws Exception {
    ApplicationContext context = initContext(WebConfig.class, ScopedController.class, ScopedProxyController.class);
    RequestMappingHandlerMapping handlerMapping = context.getBean(RequestMappingHandlerMapping.class);
    assertThat(handlerMapping.getOrder()).isEqualTo(0);
    HandlerExecutionChain chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/"));
    assertThat(chain).isNotNull();
    HandlerInterceptor[] interceptors = chain.getInterceptors();
    assertThat(interceptors).isNotNull();
    assertThat(interceptors[0].getClass()).isEqualTo(ConversionServiceExposingInterceptor.class);
    chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/scoped"));
    assertThat(chain).as("HandlerExecutionChain for '/scoped' mapping should not be null.").isNotNull();
    chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/scopedProxy"));
    assertThat(chain).as("HandlerExecutionChain for '/scopedProxy' mapping should not be null.").isNotNull();
}
Also used : AnnotationConfigWebApplicationContext(org.springframework.web.context.support.AnnotationConfigWebApplicationContext) ApplicationContext(org.springframework.context.ApplicationContext) HandlerExecutionChain(org.springframework.web.servlet.HandlerExecutionChain) HandlerInterceptor(org.springframework.web.servlet.HandlerInterceptor) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) RequestMappingHandlerMapping(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping) Test(org.junit.jupiter.api.Test)

Aggregations

HandlerInterceptor (org.springframework.web.servlet.HandlerInterceptor)30 HandlerExecutionChain (org.springframework.web.servlet.HandlerExecutionChain)14 Test (org.junit.jupiter.api.Test)10 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)8 Test (org.junit.Test)6 RequestMappingHandlerMapping (org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping)6 CorsConfiguration (org.springframework.web.cors.CorsConfiguration)5 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)4 DirectFieldAccessor (org.springframework.beans.DirectFieldAccessor)4 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)3 ArrayList (java.util.ArrayList)3 Nullable (org.springframework.lang.Nullable)3 StaticWebApplicationContext (org.springframework.web.context.support.StaticWebApplicationContext)3 MappedInterceptor (org.springframework.web.servlet.handler.MappedInterceptor)3 RequestMappingHandlerAdapter (org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter)3 Collections (java.util.Collections)2 List (java.util.List)2 Map (java.util.Map)2