dzinot / spring-boot-2-oauth2-authorization-jwt

Spring Boot 2 OAuth2 JWT Authorization server implementation with Database for Users and Clients (JPA, Hibernate, MySQL)
MIT License
134 stars 72 forks source link

Cors Origin problem #4

Open weskhaled opened 5 years ago

weskhaled commented 5 years ago

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 commented 5 years ago

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 commented 4 years ago

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 commented 4 years ago

@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 commented 1 year ago

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;
}

}