【问题标题】:spring security and spring boot 2 with cors Access-Control-Allow-Origin issuespring security 和 spring boot 2 with cors Access-Control-Allow-Origin 问题
【发布时间】:2019-03-04 08:41:45
【问题描述】:

我正在低于错误。有人可以帮助我如何在 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) 阻止跨域 使用 MIME 类型响应 http://localhost:8080/SpringGeolocation/login 应用程序/json。看 https://www.chromestatus.com/feature/5629709824032768 了解更多 详情。

spring boot 2 和 spring security

​​>

包 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");
    }

}

【问题讨论】:

标签: angularjs spring spring-boot spring-security cors


【解决方案1】:

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

@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");

    }

【讨论】:

    猜你喜欢
    • 2019-05-12
    • 2020-05-27
    • 2021-01-25
    • 2018-09-08
    • 2016-09-20
    • 2023-01-13
    • 2021-05-12
    • 2016-09-30
    • 2013-09-14
    相关资源
    最近更新 更多