настройка безопасности для среды привода Spring Boot 2.0 при обновлении с весенней загрузки 1.5 - PullRequest
0 голосов
/ 13 сентября 2018

Я переместил службу отдыха с пружинной загрузкой на использование пружинной загрузки 2.0.2 и столкнулся с проблемами с конечными точками привода. Я знаю, что весенняя загрузка убрала автоматическую конфигурацию безопасности в структуру привода весной 2.0.2. Поэтому я думаю, что мне нужно было указать безопасность, чтобы получить доступ к этим конечным точкам, но у меня уже была настроена защита, чтобы мой веб-сервис использовал JWT. подскажите, пожалуйста, как я могу включить конечную точку привода в пружинной загрузке 2.0.2, а также настроить безопасность для точек привода без влияния на Jwt

П

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.2.RELEASE</version>
</parent>
<properties>
    <jacoco.version>0.7.8</jacoco.version>
    <java.version>1.8</java.version>
    <mockito.version>2.7.22</mockito.version>
    <mybatis.version>3.4.4</mybatis.version>
    <mybatis.spring.version>1.3.1</mybatis.spring.version>
</properties>
<build>
    <finalName>${project.artifactId}</finalName>
    <resources>
        <resource>
            <filtering>true</filtering>
            <directory>src/main/resources</directory>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>integration-test</goal>
                        <goal>verify</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <!-- Uncomment this plugin after you have initialized the git repo. -->
        <!-- 
        <plugin>
            <groupId>pl.project13.maven</groupId>
            <artifactId>git-commit-id-plugin</artifactId>
        </plugin>
        -->
        <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>${jacoco.version}</version>
            <executions>
                <execution>
                    <goals>
                        <goal>prepare-agent</goal>
                        <goal>check</goal>
                        <goal>report</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <rules>
                    <rule>
                        <element>CLASS</element>

                        <limits>
                            <limit>
                                <counter>LINE</counter>
                                <value>COVEREDRATIO</value>
                                <minimum>1.00</minimum>
                            </limit>
                            <limit>
                                <counter>BRANCH</counter>
                                <value>COVEREDRATIO</value>
                                <minimum>1.00</minimum>
                            </limit>
                        </limits>
                    </rule>
                </rules>
            </configuration>
        </plugin>
    </plugins>
</build>
<reporting>
    <plugins>
        <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>${jacoco.version}</version>
            <reportSets>
                <reportSet>
                    <reports>
                        <report>report</report>
                    </reports>
                </reportSet>
            </reportSets>
        </plugin>
    </plugins>
</reporting>
<dependencies>
    <dependency>
        <groupId>com.auth0</groupId>
        <artifactId>java-jwt</artifactId>
        <version>3.2.0</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>
    <dependency>
        <groupId>com.ibm.db2.jcc</groupId>
        <artifactId>db2jcc_license_cisuz</artifactId>
        <version>DB2V11</version>
    </dependency>
    <dependency>
        <groupId>com.ibm.db2.jcc</groupId>
        <artifactId>db2jcc4</artifactId>
        <version>4.19.26</version>
    </dependency>
    <dependency>
        <groupId>com.jayway.jsonpath</groupId>
        <artifactId>json-path</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.skyscreamer</groupId>
        <artifactId>jsonassert</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>javax.inject</groupId>
        <artifactId>javax.inject</artifactId>
        <version>1</version>
    </dependency>
    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-library</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>${mockito.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>${mybatis.version}</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>${mybatis.spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.3.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth.boot</groupId>
        <artifactId>spring-security-oauth2-autoconfigure</artifactId>
        <version>2.0.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-properties-migrator</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

Интеграционный тест yaml

mybatis:
  configuration-properties:
               schema: abcd

spring:
  datasource:
     url: 
     username: 
     password: 

management:
  endpoints:
    web:
     exposure:
       include: "*"

Конфигурация безопасности ниже

 @Configuration
 @EnableResourceServer
 public class SecurityConfiguration implements 
      JwtAccessTokenConverterConfigurer {

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


 auth.inMemoryAuthentication().withUser("management").password("cfh5r64r 
  bvc54r").roles("ACTUATOR");
}


@Bean
public FilterRegistrationBean corsFilter() {
    // Set CORS configuration to allow cross-origin requests by default.
    // Addtionally add the HTTP OPTIONS method for pre-flight requests.
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    corsConfiguration.applyPermitDefaultValues();
    corsConfiguration.setAllowCredentials(true);
    corsConfiguration.addAllowedMethod(HttpMethod.GET);
    corsConfiguration.addAllowedMethod(HttpMethod.POST);
    corsConfiguration.addAllowedMethod(HttpMethod.PUT);
    corsConfiguration.addAllowedMethod(HttpMethod.OPTIONS);

    UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
    urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);

    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(
            new CorsFilter(urlBasedCorsConfigurationSource));
    filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);

    return filterRegistrationBean;
}


@Override
public void configure(JwtAccessTokenConverter converter) {
    converter.setAccessTokenConverter(new DefaultAccessTokenConverter() {


        @Override
        public OAuth2Authentication extractAuthentication(Map<String, ?> 
           map) {
            Object i = map.get();
            Object e = map.get();

            if (issuerClaim == null || !issuer.equals(issuerClaim) || expirationClaim == null) {
                throw new InvalidTokenException("");
            }

            return super.extractAuthentication(map);
        }
    });
}

}

Я пытаюсь написать интеграционные тесты, как показано ниже

@RunWith(SpringRunner.class)
 @SpringBootTest(webEnvironment = WebEnvironment.MOCK)
 @AutoConfigureMockMvc
@ActiveProfiles("it")
@DirtiesContext
 public class SecurityConfigurationIT {

@Test
@WithMockUser(roles = VALID_ACTUATOR_ROLE)
public void should_be_authorized_for_actuator() throws Exception {
    mockMvc.perform(get(LOGGERS).header(HttpHeaders.ORIGIN, 
     ORIGIN)).andExpect(status().isOk())                 
       .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, 
      ORIGIN));
}

@Test
@WithMockUser(roles = INVALID_ACTUATOR_ROLE)
public void should_fail_as_forbidden_for_actuator() throws Exception {
    mockMvc.perform(get(LOGGERS).header(HttpHeaders.ORIGIN, 
   ORIGIN)).andExpect(status().isForbidden())

   .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, 
    ORIGIN));
}

}

Когда я пытаюсь запустить его, получая 401, но это работает в весенней загрузке 1.5.x

MockHttpServletRequest:
  HTTP Method = GET
  Request URI = /actuator/info
   Parameters = {}
      Headers = {Origin=[test.com]}
         Body = null
Session Attrs = {}

Обработчик: Тип = ноль

Async:
Async started = false
 Async result = null

 Resolved Exception:
         Type = null

     ModelAndView:
    View name = null
         View = null
        Model = null

  FlashMap:
   Attributes = null

  MockHttpServletResponse:
       Status = 401
Error message = null
      Headers = {Vary=[Origin, Access-Control-Request-Method, Access- 
        Control-Request-Headers], Access-Control-Allow-Origin=[test.com], 
     Access-Control-Allow-Credentials=[true], Cache-Control=[no-store], 
   Pragma=[no-cache], WWW-Authenticate=[Bearer realm=", 
 error="unauthorized", error_description="Full 
       authentication is required to access this resource"], Content-Type= 
   [application/json;charset=UTF-8], X-Content-Type-Options=[nosniff], X- 
      XSS-Protection=[1; mode=block], X-Frame-Options=[DENY]}
 Content type = application/json;charset=UTF-8
         Body = {"error":"**unauthorized","error_description":"Full 
     authentication is required to access this resource"**}
Forwarded URL = null

Перенаправленный URL = ноль

1 Ответ

0 голосов
/ 13 сентября 2018

если у вас есть http защита в вашем pom, вы должны переопределить configure, иначе по умолчанию потребуется аутентификация и будет выброшено 401 для всех конечных точек.

, поэтому вы должны иметь ниже config и обрабатывать в соответствии с вашими конечными требованиямиточки и роли, вам также может потребоваться вызвать jwtAccessTokenConverterConfiguration для получения конечных точек, которые необходимы для проверки аутентификации. (Я не думаю, что jwtAccessTokenConverterConfiguration даже вызывается, вы отлаживали?)

ниже приведен пример, которыйпередаст все ваши конечные точки из аутентификации, измените в соответствии с вашими потребностями.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/**").permitAll();
    }

}
...