首先,我已经检查了this page的问题。我尝试了他的解决方案,但最后,我仍然遇到同样的问题。
XMLHttpRequest cannot load http://localhost:8080/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 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;
}
如果身份验证成功,我也想返回一个 boolean 值,但我真的不知道如何知道它是否有效,所以我现在就这样做(而且它总是正确的)。
然后,在 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 之间工作。
最佳答案
将以下内容添加到您的配置方法
.cors().and()
关于java - 带有 Spring Boot 和 Spring Security 的 Angular2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42552600/