Programing

CORS : 자격 증명 모드는 '포함'입니다.

lottogame 2020. 11. 22. 18:52
반응형

CORS : 자격 증명 모드는 '포함'입니다.


네, 당신이 무슨 생각을하는지 알고 있습니다. 또 다른 CORS 질문이지만 이번에는 난처합니다.

따라서 시작하려면 실제 오류 메시지 :

XMLHttpRequest는 http : //localhost/Foo.API/token을 로드 할 수 없습니다 . 요청의 자격 증명 모드가 'include'인 경우 응답의 'Access-Control-Allow-Origin'헤더 값은 와일드 카드 '*'가 아니어야합니다 . 따라서 원본 ' http : // localhost : 5000 '은 액세스가 허용되지 않습니다. XMLHttpRequest에 의해 시작된 요청의 자격 증명 모드는 withCredentials 속성에 의해 제어됩니다.

자격 증명 모드의 의미 가 '포함' 인지 잘 모르겠습니다 .

따라서 우편 배달부에서 요청을 수행 할 때 이러한 오류가 발생 하지 않습니다 .

여기에 이미지 설명 입력

하지만 angularjs 웹 앱을 통해 동일한 요청에 액세스 할 때이 오류로 인해 당황합니다. 여기 내 angualrjs 요청 / 응답이 있습니다. 보시다시피 응답은 OK 200이지만 여전히 CORS 오류가 발생합니다.

Fiddler 요청 및 응답 :

다음 이미지는 웹 프런트 엔드에서 API 로의 요청 및 응답을 보여줍니다.

바이올리니스트

그래서 내가 온라인에서 읽은 다른 모든 게시물을 보면 내가 옳은 일을하고있는 같아서 오류를 이해할 수없는 것입니다. 마지막으로 angualrjs (로그인 팩토리)에서 사용하는 코드는 다음과 같습니다.

여기에 이미지 설명 입력

API의 CORS 구현-참조 목적 :

사용 된 방법 1 :

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        EnableCrossSiteRequests(config);
    }

    private static void EnableCrossSiteRequests(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute("*", "*", "*")
        {
            SupportsCredentials = true
        };
        config.EnableCors(cors);
    }
}

사용 된 방법 2 :

public void Configuration(IAppBuilder app)
{
    HttpConfiguration config = new HttpConfiguration();

    ConfigureOAuth(app);

    WebApiConfig.Register(config);
    app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
    app.UseWebApi(config);

}

미리 감사드립니다!


문제는 Angular 코드에서 비롯됩니다.

When withCredentials is set to true, it is trying to send credentials or cookies along with the request. As that means another origin is potentially trying to do authenticated requests, the wildcard ("*") is not permitted as the "Access-Control-Allow-Origin" header.

You would have to explicitly respond with the origin that made the request in the "Access-Control-Allow-Origin" header to make this work.

I would recommend to explicitly whitelist the origins that you want to allow to make authenticated requests, because simply responding with the origin from the request means that any given website can make authenticated calls to your backend if the user happens to have a valid session.

I explain this stuff in this article I wrote a while back.

So you can either set withCredentials to false or implement an origin whitelist and respond to CORS requests with a valid origin whenever credentials are involved


Customizing CORS for Angular 5 and Spring Security (Cookie base solution)

On the Angular side required adding option flag withCredentials: true for Cookie transport:

constructor(public http: HttpClient) {
}

public get(url: string = ''): Observable<any> {
    return this.http.get(url, { withCredentials: true });
}

On Java server-side required adding CorsConfigurationSource for configuration CORS policy:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        // This Origin header you can see that in Network tab
        configuration.setAllowedOrigins(Arrays.asList("http:/url_1", "http:/url_2")); 
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        configuration.setAllowedHeaders(Arrays.asList("content-type"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()...
    }
}

Method configure(HttpSecurity http) by default will use corsConfigurationSource for http.cors()


If you are using CORS middleware and you want to send withCredential boolean true, you can configure CORS like this:

var cors = require('cors');
app.use(cors({credentials: true, origin: 'http://localhost:5000'}));


If it helps, I was using centrifuge with my reactjs app, and, after checking some comments below, I looked at the centrifuge.js library file, which in my version, had the following code snippet:

if ('withCredentials' in xhr) {
 xhr.withCredentials = true;
}

After I removed these three lines, the app worked fine, as expected.

Hope it helps!


If you're using .NET Core, you will have to .AllowCredentials() when configuring CORS in Startup.CS.

Inside of ConfigureServices

services.AddCors(o => {
    o.AddPolicy("AllowSetOrigins", options =>
    {
        options.WithOrigins("https://localhost:xxxx");
        options.AllowAnyHeader();
        options.AllowAnyMethod();
        options.AllowCredentials();
    });
});

services.AddMvc();

Then inside of Configure:

app.UseCors("AllowSetOrigins");
app.UseMvc(routes =>
    {
        // Routing code here
    });

For me, it was specifically just missing options.AllowCredentials() that caused the error you mentioned. As a side note in general for others having CORS issues as well, the order matters and AddCors() must be registered before AddMVC() inside of your Startup class.

참고URL : https://stackoverflow.com/questions/42803394/cors-credentials-mode-is-include

반응형