spring-security 跨源API Sping Boot 安全性[重复]

fdx2calv  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(211)

此问题在此处已有答案

CORS issue - No 'Access-Control-Allow-Origin' header is present on the requested resource(8个答案)
两个月前关门了。
我正在尝试调用安全资源。我在所有rest controllers中使用了@CrossOrigin(origins = "*")。但是我得到cross origin错误
我不能用“GET”方法调用“http://localhost:8081/ifrs/api/v1/period”,但我可以调用“getJwtToken”,因为它不是安全的。
我配置是:

@Configuration
public class SecuirtyConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtFilter jwtFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
            .cors().and()
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/ifrs/api/v1/user/token").permitAll()

            .anyRequest().authenticated()

            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)

            .and()
            .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)         
            ;

        http.exceptionHandling().authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));

    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

}

和JWT配置:

@Component
public class JwtFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserDomainService userDomainService;

    @Override
    protected void doFilterInternal(
            HttpServletRequest request, 
            HttpServletResponse response, 
            FilterChain filterChain) throws ServletException, IOException {

        try {

            String token = request.getHeader("Authorization");

            String jwtToken = null;
            if ( token != null ) {

                if ( token.startsWith("Bearer ") ) {

                    jwtToken = token.replace("Bearer ", "");

                    String username = jwtUtils.getUsername(jwtToken);
                    username = username.trim();

                    // isUserAuthentication
                    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

                    if (username != null && authentication == null) {
                        User user = (User) userDomainService.loadUserByUsername(username);

                        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());

                        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
                    }

                } else if ( token.startsWith("Basic ") ) {

                    jwtToken = token.replace("Basic ", "");

                    Base64 codec = new Base64();
                    byte[] decoded = codec.decode(jwtToken);

                    String[] userAndPass = new String(decoded).split(":");
                    String username = userAndPass[0];
                    String password = userAndPass[1];

                    request.setAttribute("username", username);
                    request.setAttribute("password", password);

                }

            }

            filterChain.doFilter(request, response);

        } catch (ExpiredJwtException e) {
            throw e;

        } catch (Exception e) {
            throw e;

        }

    }

}

我测试了所有的方法来修复它。@CrossOrigin(origins = "*")只适用于不安全的资源。如何修复它?
谢谢

lskq00tm

lskq00tm1#

我更改了代码
类安全配置--〉相关配置源:

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.addAllowedHeader("*");    // new Line
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

并配置(HttpSecurity http):

.cors().and()
    .csrf().disable()
    .authorizeRequests()
    .antMatchers(HttpMethod.OPTIONS).permitAll()
    .antMatchers("/ifrs/api/v1/user/token").permitAll()

谢谢

相关问题