Reputation: 53
First of all, I've already checked the question at this page and I tried that solution, but at the end, I still have the same issue.
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. Originhttp://localhost:3000
is therefore not allowed access. The response had HTTP status code 403.
However, I put an access-control
everywhere so I don't understand why it's like this.
My code looks like this (I hope I will put enough for you):
In Angular, my
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;
}
I also want to return a boolean
if the authentication succeed, but I don't really know how to. If it works, so I do it like that for now (and it's always true).
Then, in Java, I have this code:
@Configuration
@EnableWebMvc
class WebConfig extends WebMvcConfigurerAdapter {
}
then for the security, I got this:
@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;
}
In my 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;
}
}
So, any idea on what is the problem? Or on how to make an Angular 2 app with Spring Boot and Spring Security? Because everything works between Spring Boot and Angular except when I add the security.
Upvotes: 1
Views: 2236