当前位置: 首页 > 知识库问答 >
问题:

spring security和spring boot 2带有cors Access-Control-Allow-Origin问题

冉锋
2023-03-14

我得到了低于误差。有没有人可以帮助我如何在spring boot和spring Security中配置cors。在AngularJS中有没有任何事情我必须从UI端做。

加载http://localhost:8080/springgeolocation/login失败:请求的资源上没有“access-control-allow-origin”标头。因此,不允许访问源“http://localhost:8000”。(索引):70{ReadyState:0,GetResponseHeader:.,GetAllResponseHeaders:.,SetRequestHeader:.,OverrideMimetype:,, …}all.min.js:9566跨源读取阻塞(CORB)阻塞的跨源响应http://localhost:8080/SpringGeolocation/login with MIME类型application/json。详见https://www.cromestatus.com/feature/5629709824032768。

包com.geo.config;

import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import com.geo.security.LogoutSuccessHandler;
import com.geo.security.RestUnauthorizedEntryPoint;


@EnableWebSecurity
@Configuration
//@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(SecurityConfiguration.class);

    public static final String REMEMBER_ME_KEY = "rememberme_key";

    public SecurityConfiguration() {
        super();
        logger.info("loading SecurityConfig ................................................ ");
    }

    @Autowired
    private RestUnauthorizedEntryPoint restAuthenticationEntryPoint;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private AccessDeniedHandler restAccessDeniedHandler;

    @Autowired
    private AuthenticationSuccessHandler restAuthenticationSuccessHandler;

    @Autowired
    private AuthenticationFailureHandler restAuthenticationFailureHandler;

    @Autowired
    private RememberMeServices rememberMeServices;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Autowired
    LogoutSuccessHandler logoutSuccessHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().authorizeRequests().antMatchers("/user/**").hasAnyAuthority("admin", "user")
                .anyRequest().authenticated().antMatchers("/role/**").hasAnyAuthority("admin")

                .and().exceptionHandling()
                 .authenticationEntryPoint(restAuthenticationEntryPoint)
                .accessDeniedHandler(restAccessDeniedHandler).and().formLogin().loginPage("/login") // by putting this
                                                                                                    // or by applying
                                                                                                    // authentication
                // entrypoint default login page would not appear
                // .loginProcessingUrl("/authenticate")
                .successHandler(restAuthenticationSuccessHandler).failureHandler(restAuthenticationFailureHandler)
                .usernameParameter("username").passwordParameter("password").permitAll().and().logout()
                .logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler).deleteCookies("JSESSIONID").permitAll()
                .and().rememberMe().rememberMeServices(rememberMeServices).rememberMeParameter("remember-me")
                .rememberMeCookieName("remember-me").key(REMEMBER_ME_KEY);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
        web.ignoring().antMatchers("/resources/**", "/index.html", "/login.html", "/partials/**", "/template/**", "/",
                "/error/**");
    }



}
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.datasource.url=jdbc:mysql://localhost:3306/googlemap
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true


# logging
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n
logging.level.org.hibernate.SQL=debug


logging.level.root=info
#server.error.whitelabel.enabled=false

spring.aop.proxy-target-class=false

management.endpoints.web.cors.allowed-origins=http://localhost:8080
management.endpoints.web.cors.allowed-methods=GET,POST,PUT,DELETE,HEAD

@Configuration
@EnableWebMvc
@ComponentScan("com.geo")
public class AppConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD")
                .allowedOrigins("http://localhost:8080");
    }

}

共有1个答案

仲孙华奥
2023-03-14

添加允许标头和公开标头应该可以工作。

@Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS")
                .allowedOrigins("http://localhost:8080")
                .allowedHeaders("Authorization", "Cache-Control", "Content-Type", "Accept", "X-Requested-With", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Origin")
            .exposedHeaders("Access-Control-Expose-Headers", "Authorization", "Cache-Control", "Content-Type", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Origin");

    }
 类似资料:
  • XMLHttpRequest无法加载http://localhost:8080/nobelgrid/api/users/create/。请求的资源上没有“访问-控制-允许-来源”标头。因此,不允许访问源'http://localhost:63342'。响应的HTTP状态代码为500。 谁能帮帮我吗? 更新: 但我还有一个错误。我会做另一个问题,因为我认为这是一个不同的论点。 提前感谢!

  • Access-Control-Allow-Origin响应 header 指示是否该响应可以与具有给定资源共享原点。 Header type Response header Forbidden header name no 语法 Access-Control-Allow-Origin: *Access-Control-Allow-Origin: <origin> 指令 * 对于没有凭据的请求,服务

  • 问题内容: 这可能是一个简单的(一系列)问题,但我无法解决。 我正在尝试从托管在我网站上的Web应用程序访问github api。简而言之,这是代码: 如果我将浏览器指向在我的保管箱帐户上载的这个简单页面,则一切正常。相反,如果我将浏览器指向该网站上上传的这个简单页面,则会得到臭名昭著的异常: 因此,问题是: 为什么在Dropbox上可以使用? 我了解使用CORS即使在网站上也可以使用。这是我的A

  • null 服务器的响应如下: XMLHttpRequest无法加载http://nqatalog.negroesquisso.pt/login.php。Access-Control-Allow-Origin不允许Origin 。 如何解决此问题?

  • 问题内容: 我是Ajax的新手,只是受过此跨域调用的任务。我们的网页上有一个文本框,用户可用来执行公司名称搜索。通过单击文本框旁边的按钮,将请求Ajax调用。不幸的是,Web服务位于单独的域中,因此自然会引起问题。 以下是我使这项工作的最佳尝试。我还要注意,此调用的目的是以XML格式返回结果,该结果将在请求的一部分中进行解析。 这又是错误消息: 对于解决方法,我不知所措,将不胜感激任何想法。 问题

  • 问题内容: 将web.xml移植到Java配置后出现以下问题 根据一些Spring参考,尝试了以下尝试: 所选择的值来自有效的web.xml过滤器: 有什么想法为什么Spring java config方法不能像web.xml文件那样工作? 问题答案: 将CorsMapping从更改方法。 为整个应用程序启用CORS很简单: 你可以轻松更改任何属性,以及仅将此CORS配置应用于特定的路径模式: 控