Я получаю ошибку ниже.Может ли кто-нибудь помочь мне, как настроить Cors в весенней загрузке с весенней безопасности.Есть ли что-то, что я должен сделать со стороны пользовательского интерфейса в angularjs.
Не удалось загрузить 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 с приложением MIME-типа / JSON.См. https://www.chromestatus.com/feature/5629709824032768 для получения более подробной информации.
пружинный башмак 2 вместе с пружинной защитой
пакет 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");
}
}