我遇到了错误。有人可以帮助我如何在具有弹簧安全性的弹簧靴中配置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了解更多 详细信息。
包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");
}
}
答案 0 :(得分:2)
添加allow标头和暴露标头应该可以。
@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");
}