SpringBoot+Spring Security無法實現跨域解決辦法
阿新 • • 發佈:2019-02-08
未使用Security時跨域:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry ;
import org.springframework.web.servlet.config.annotation.*;
@Configuration
@AutoConfigureBefore(SecurityConfig.class)
public class MyMvcConfigurer implements WebMvcConfigurer {
public void addCorsMappings(CorsRegistry registry){
LOGGER.info("跨域已設定");
registry.addMapping("/**")
.allowedOrigins ("*")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}
整合Security時發現只用上述方法前後端分離時仍存在跨域問題,解決方法如下:
@Configuration
@AutoConfigureBefore(Swagger2Configuration.class)
@EnableWebSecurity
@EnableGlobalMethodSecurity (prePostEnabled = true)
@Order(-1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginProcessingUrl("/user/login")
.loginPage("/singIn.html")
.successHandler(moyuAuthenticationSuccessHandler)
.failureHandler(moyuAuthenticationFailureHandler)
.and()
.apply(moyuSocialSecurityConfig)
.and()
.rememberMe()
.tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(3600*24*7)
.userDetailsService(userDetailsService)
.and()
.authorizeRequests()
.antMatchers("/user/login","/login","/singIn.html","**","/**").permitAll()
.anyRequest()
.authenticated()
.and()
.cors()
.and()
.csrf().disable();
}
}
重點加入程式碼:
.and()
.cors()//新加入
.and()
.csrf().disable();