CrossOrigin с защитой http с использованием токена jwt при загрузке Spring - PullRequest
0 голосов
/ 05 мая 2020

У меня есть проблема с безопасностью crossorigin и http в моем приложении весенней загрузки. Я хочу использовать http-безопасность, когда аннотирую метод с помощью @crossorigin в моем классе контроллера. Но это не работает, безопасность всегда срабатывает, даже если метод не использует @crosorigin.

Можно ли это исправить?

Класс Jwtautoconfig:

@ManagementContextConfiguration
@ConditionalOnProperty(name = {"af.security.active"}, havingValue = "true")
@Import({EnvironmentConfig.class, JwkRepository.class, JwtTokenUtil.class, 
JwtAuthenticationProvider.class})
@EnableWebSecurity
@EnableConfigurationProperties(JwtSecurityProperties.class)
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Order(Ordered.HIGHEST_PRECEDENCE)
public class JwtAutoConfig extends WebSecurityConfigurerAdapter {


@Value("${af.security.jwt.white-list}")
private  String[] ignoredPaths;

@Value("${af.security.job-seeker-role:arbetssökande}")
private String jobSeekerRole;

@Value("${af.security.officer-role:handläggare}")
private String officer;

@Bean(name = "jwtauthenticationentrypoint")
public JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint() {

    return new JwtAuthenticationEntryPoint();
}

@Bean
public JwtSecurityHelper securityHelper(){
    return new JwtSecurityHelper(jobSeekerRole, officer);
}



@Bean
public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
    JwtAuthenticationTokenFilter authenticationTokenFilter = new JwtAuthenticationTokenFilter();
    authenticationTokenFilter.setAuthenticationManager(authenticationManager());
    authenticationTokenFilter.setAuthenticationSuccessHandler(new JwtAuthenticationSuccessHandler());
    return authenticationTokenFilter;
}

@Override
public void configure(HttpSecurity http) throws Exception {
    http.requestMatchers()
            .and()
            .authorizeRequests()
            .antMatchers("/**")
            .authenticated()
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .csrf()
            .disable();

    // Custom JWT based security filter
    http.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);

    // disable page caching
    http.headers().cacheControl();
}

@Override
public void configure(WebSecurity web) {
    final String[] trimmedIgnoredPaths = Stream.of(ignoredPaths)
            .map(String::trim)
            .toArray(String[]::new);

    web.ignoring()
            .antMatchers(HttpMethod.OPTIONS,"/**")
            .and()
            .ignoring().antMatchers(trimmedIgnoredPaths);
}


private Config hazelCastConfig(){
    Config config = new Config();
    config.setInstanceName("app-cache")
            .setNetworkConfig(new NetworkConfig()
                    .setJoin(new JoinConfig()
                            .setMulticastConfig(new MulticastConfig()
                                    .setEnabled(false)
                            )
                    )
            )
            .addMapConfig(
                    new MapConfig()
                            .setName("object-cache")
                            .setMaxSizeConfig(new MaxSizeConfig(10, MaxSizeConfig.MaxSizePolicy.FREE_HEAP_SIZE))
                            .setEvictionPolicy(EvictionPolicy.LRU)
                            .setStatisticsEnabled(true)
                            .setTimeToLiveSeconds(14400));
    return config;
}

@Bean(name="hazelcast")
public HazelcastInstance hazelcastInstance() {

    HazelcastInstance hazelcastInstance = new HazelcastInstanceFactory(hazelCastConfig()).getHazelcastInstance();
    return hazelcastInstance;
}

}

Класс CorsConfig:

@Configuration
public class CorsConfig {

@Bean
public WebMvcConfigurer corsConfigurer()
{
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowedMethods("POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "DELETE", "GET" )
                    .allowCredentials(true);
        }
    };
}
}

И это метод в моем классе контроллера:

    @ApiOperation(value = "Hämtar alla frånvaron för en lista med användare")
@PostMapping(path= "/hamta-alla-franvaron", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<ExternalFranvaroDTO>> hamtaAllaFranvaron(
        @ApiParam(value = "Identitet objekt som innehåller en lista av PISA_ID", required = true)
        @Valid @RequestBody IdentitetForm identitet){
    logger.info("MOTTAGET Rest-anrop (/hamta-alla-franvaron) Hamtar alla franvaron");
    List<ExternalFranvaroDTO> externalFranvaroDTOLista = new ArrayList<>();
    List<Franvaro> franvaron = franvaroService.hamtaAllaPagaendeOchNyaFriskskrivnaFranvaron(identitet.getPisaIds());

    if(franvaron.isEmpty()) {
        logger.debug("Inga pågende sjuk/vab anmälan");
        return ResponseEntity.noContent().build();
    }
    franvaron.forEach( franvaro -> {
        ExternalFranvaroDTO externalFranvaroDTO = transformeraTillExternalFranvaroDTO(franvaro);
        externalFranvaroDTOLista.add(externalFranvaroDTO);
    });

    return ResponseEntity.ok().body(externalFranvaroDTOLista);
}

Теперь я хочу использовать HTTP-безопасность только при использовании @ crossorigin

1 Ответ

0 голосов
/ 06 мая 2020

Я не вижу причин, почему вы хотели бы объединить это так.

Вместо этого вы должны применить безопасность к указанным c конечным точкам и вместо этого настроить фильтр cors в Spring security настройки его глобально, как вы это сделали.

Если вы читаете документацию по безопасности Spring в разделе HttpSecurity , вы можете использовать antMatcher и сопоставить конечные точки, используя синтаксис ant

protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests(authorize -> authorize
        .antMatcher( // Here you can define endpoints using ant matching
            "**/foo/**",
            "**/bar/**"
        )
        .authenticated()
    )

    ... // rest of configuration
}

Вы также можете определить фильтр CORS с помощью пружинной защиты

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // by default uses a Bean by the name of corsConfigurationSource
            .cors(withDefaults())
            ...
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

Вы даже можете активировать и использовать встроенный фильтр jwt и настройте этот фильтр с помощью вашего собственного конвертера et c. et c.

protected void configure(HttpSecurity http) {
    http
        .authorizeRequests(authorize -> authorize
            .anyRequest().authenticated()
        )
        .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
}

        // or add a custom converter
        .oauth2ResourceServer(oauth2 -> oauth2
            .jwt(jwt -> jwt
                // adding a custom converter here
                .jwtAuthenticationConverter(myConverter())
            )
        );

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...