SpringSecurity 实现授权码模式遇到了跨域问题,在网上找了一些解决办法,只能解决password模式的跨域问题,但是在授权码模式无法进行登录页跳转,
错误信息:
错误信息
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sun Nov 24 13:05:53 CST 2019
There was an unexpected error (type=Internal Server Error, status=500).
User must be authenticated with Spring Security before authorization can be completed.
代码如下:
SecurityConfig代码
@EnableWebSecurity(debug = true)
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(-1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().loginPage("/signIn.html")
.loginProcessingUrl("/authentication/form")
.and()
.authorizeRequests()
.antMatchers("/signIn.html","/authentication/form","/oauth/**").permitAll()
.anyRequest()
.fullyAuthenticated().and()
.requestMatchers().antMatchers(HttpMethod.OPTIONS, "/oauth/token")
.and()
.cors()
.and()
.csrf().disable();
}
}
全局过滤器代码
@Configuration
public class GlobalCorsConfiguration {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
// corsConfiguration.addExposedHeader("head1");
//corsConfiguration.addExposedHeader("Location");
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}
前端代码:
$.ajax({
url: 'http://127.0.0.1:8090/oauth/token',
xhrFields: {
withCredentials: true
},
contentType:'application/x-www-form-urlencoded;charset=UTF-8',
crossDomain: true,
data: {'grant_type':'authorization_code','code':s["code"],'scope':'all','redirect_uri':'http://127.0.0.1/manage/pages/index.html'},
type: 'POST',
//dataType:'JSON',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + window.btoa("imooc:imoocsecret"));
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
},
success: function (data) {
},
error: function (xhr) {
console.log(xhr)
}
});