首先,我已经在this page检查了问题并尝试了他的解决方案,但最后,我仍然遇到同样的问题。
XMLHttpRequest无法加载http://localhost:8080/login。 对预检请求的响应未通过访问控制检查: 请求的资源上不存在“Access-Control-Allow-Origin”标头。 因此,不允许原点“http://localhost:3000”访问。 响应的HTTP状态代码为403。
但是,我把access-control
放在任何地方,所以我不明白为什么会这样。
我的代码看起来像这样(我希望我会为你提供足够的代码):
在Angular中,我的login.service.ts
:
check(name: string, password: string): boolean {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Access-Control-Allow-Origin','*');
let options = new RequestOptions({headers:headers,withCredentials:true});
if(this.http.post(this.baseUrl,
`username=${name}&password=${password}`,
{headers:headers})
.toPromise().then(response=> {
return {}
}))
return true;
return false;
}
如果身份验证成功,我也想返回一个布尔值,但我真的不知道如何知道它是否有效,所以我现在这样做(并且它总是如此)。
然后,在Java中,我有这段代码:
@Configuration
@EnableWebMvc
class WebConfig extends WebMvcConfigurerAdapter {
}
然后为了安全起见,我得到了这个:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private RESTLoginSuccessHandler loginSuccessHandler;
@Autowired
private RestLogoutSuccessHandler logoutSuccessHandler;
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
//deactivate CSRF and use custom impl for CORS
httpSecurity
.cors.and()
.csrf().disable()
.addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class);
//authorize, authenticate rest
httpSecurity
.authorizeRequests()
.anyRequest().hasRole("USER")
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.formLogin()
.usernameParameter("username")
.passwordParameter("password")
.loginPage("/login")
.successHandler(loginSuccessHandler)
.permitAll()
.and()
.logout()
.logoutSuccessHandler(this.logoutSuccessHandler)
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("rano").password("1234").roles("USER");
auth.inMemoryAuthentication().withUser("admin").password("admin").roles("USER", "ADMIN");
}
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:8080","http://localhost:3000"));
configuration.setAllowedMethods(Arrays.asList("PUT","DELETE","POST"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
在我的LoginSuccessHandler中:
@Component
public class RESTLoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private RequestCache requestCache = new HttpSessionRequestCache();
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
org.springframework.security.core.Authentication authentication) throws IOException, ServletException {
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest == null) {
clearAuthenticationAttributes(request);
return;
}
String targetUrlParam = getTargetUrlParameter();
if (isAlwaysUseDefaultTargetUrl()
|| (targetUrlParam != null && StringUtils.hasText(request.getParameter(targetUrlParam)))) {
requestCache.removeRequest(request, response);
clearAuthenticationAttributes(request);
return;
}
clearAuthenticationAttributes(request);
}
public void setRequestCache(RequestCache requestCache) {
this.requestCache = requestCache;
}
}
那么,关于什么是问题的任何想法?或者如何使用Spring Boot和Spring Security制作Angular2应用程序?因为除了添加安全性之外,一切都在Spring Boot和Angular之间起作用。
答案 0 :(得分:1)
将以下内容添加到配置方法
.cors().and()