使用Spring启动时使用jwt令牌的具有http安全性的CrossOrigin

问题描述 投票:0回答:1

我在Spring Boot应用程序中遇到有关跨域和http安全性的问题。在控制器类中使用@crossorigin注释方法时,我想使用http安全性。但是它无法正常工作,即使该方法未使用@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);
}

现在我只想在使用@crossorigin时使用http安全性

java spring-boot spring-security cors jwt
1个回答
0
投票

我不知道您为什么要像这样将其合并。

您应该将安全性应用于特定端点,并在spring安全性中配置cors过滤器,而不要像这样那样全局设置。

如果您阅读HttpSecurity下的spring security文档,则可以使用antMatcher并使用ant syntax匹配端点

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 filter

@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 filter,也可以使用自己的转换器等自定义过滤器,等等。>>

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安全文档确实非常好,您应该始终首先将其用作信息来源。

© www.soinside.com 2019 - 2024. All rights reserved.