Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cors Origin problem #4

Open
weskhaled opened this issue Jan 13, 2019 · 4 comments
Open

Cors Origin problem #4

weskhaled opened this issue Jan 13, 2019 · 4 comments

Comments

@weskhaled
Copy link

i have Cors Origin problem with angular services

Access to XMLHttpRequest at 'http://localhost:9999/oauth/token' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

How it resoleved ??

@jonathanlermitage
Copy link

jonathanlermitage commented May 13, 2019

You should configure CORS:

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Collections.singletonList("*")); // <-- you may change "*"
        configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(Arrays.asList(
            "Accept", "Origin", "Content-Type", "Depth", "User-Agent", "If-Modified-Since,",
            "Cache-Control", "Authorization", "X-Req", "X-File-Size", "X-Requested-With", "X-File-Name"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

@carbomax
Copy link

carbomax commented Oct 9, 2020

I fixed the problem with Cors and Oauth2
My configuration:

@OverRide
public void configure(HttpSecurity http) throws Exception {
http.headers().frameOptions().disable()
.and()
.authorizeRequests()
.antMatchers( "/pepeganga/security/oauth/").permitAll()
.antMatchers(HttpMethod.GET, "/
").permitAll()
.antMatchers(HttpMethod.POST, "/").permitAll()
.antMatchers(HttpMethod.PUT, "/
").permitAll()
.antMatchers(HttpMethod.DELETE, "/**").permitAll()
.antMatchers(HttpMethod.OPTIONS, "*").permitAll()
.anyRequest().authenticated().and().cors().configurationSource(corsConfigurationSource());
}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Collections.singletonList("*")); // <-- you may change "*"
    configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
    configuration.setAllowCredentials(true);
    configuration.setAllowedHeaders(Arrays.asList(
            "Accept", "Origin", "Content-Type", "Depth", "User-Agent", "If-Modified-Since,",
            "Cache-Control", "Authorization", "X-Req", "X-File-Size", "X-Requested-With", "X-File-Name"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

@Bean
public FilterRegistrationBean<CorsFilter> corsFilterRegistrationBean() {
    FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(corsConfigurationSource()));
    bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
    return bean;
}

---FrontEnd---

URI = environment.URI_ROOT;
URI_AUTH = ${this.URI}/security/oauth/token;

httpHeaders = new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + btoa('pepeganga_app' + ':' + 'passss')
});

constructor(public http: HttpClient) { }

login(user: User): Observable {
const params = new URLSearchParams();
params.set('grant_type', 'password');
params.set('username', user.email);
params.set('password', user.password);
return this.http.post(this.URI_AUTH, params.toString(), { headers: this.httpHeaders })
}

@joenan
Copy link

joenan commented Nov 10, 2020

@luissangge, Your solution is the very best. I had same issue with Angular and SpringBoot Security and i couldnt solve cross Origin issues. Your solution is the very best I have seen online. Thank you for posting this

@RMalyadri
Copy link

RMalyadri commented Dec 12, 2022

Fixed with sprig security, spring boot 2.7.6, spring cloud, oauth2 resource server and angular

package com.hsbc.customer.config;

import java.util.Arrays;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@configuration
public class SecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
	http.csrf().disable();
	http.authorizeRequests(authReq -> authReq.anyRequest().authenticated())
			.oauth2ResourceServer(oauthJwt -> oauthJwt.jwt());
	http.cors().configurationSource(corsConfigurationSource());
	return http.build();
}

private CorsConfigurationSource corsConfigurationSource() {
	CorsConfiguration configuration = new CorsConfiguration();
	configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
	configuration.setAllowedMethods(Arrays.asList("*"));
	configuration.setAllowedHeaders(Arrays.asList(HttpHeaders.AUTHORIZATION, HttpHeaders.CONTENT_TYPE));
	UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
	source.registerCorsConfiguration("/**", configuration);
	return source;
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants