AspNetCore source middleware resolve _1_CORS

Outline

What is cross-domain

In the former separate back-end development, cross-domain problem is that we often encounter. The so-called cross-domain, that is, for security reasons, A domain is an Ajax request to the B domain, the browser will refuse, throw similar to the following error.

image

JSONP

JSONP is not a standard cross-domain protocol, more like a clever programmer opportunistic approach. Js principle of this approach is that there is no cross-domain restrictions, you think you are not referenced bootstrap.js network address can be put to use.
In fact, all src attributes are not cross-domain restrictions, such as cross-domain images using the img tag is not a problem.

Generally divided into four-step process.

  • First, data formats and conventions callback function name
  • A Web site references js B site
  • B website with an appointment to the callback function will wrap up the data, return js A reference in
  • A website for the data in the callback function

The advantage of this scheme is that compatibility is better, very old ie can support, after all, just based on a technique js, and no new technology or protocol.
More obvious shortcomings, only supports GET, to understand more awkward, the call fails not return http status code, there are some security problems.

HEARTS

CORS stands for Cross Origin Resource Sharing, which translates to a cross-domain resource sharing.

The essential problem is the browser cross-domain security reasons, preventing the client cross-domain requests. But in the end, the client requests it safe is not the final say of the server, the server says our house rice you eat lightly, browser stop, this is not it get in the way, when you also own a property owner it?

But the browser can not just release, after all, not only have serious surfing the guests, there are thieves, really have a problem Tucao property pulpy. The browser that the server, the client go to your house to eat rice, you have to tell me you do not agree with ah, the server ye that I tell you ah, I can not personally directed at the guard post to shout I'M OK it. Browser say that we put forward a protocol of it, the entire Internet community are by this specification, you just push the format back to me.

This agreement is the CORS.

graph LR; A (Client) -> B (without Orgin cross-domain request); B -> C (browser to refuse); A -> D (cross-domain request with Origin); D -> E (back end services whitelist); E -> F (whitelist); E -> G (outer white list); F -> H (browser release); G -> C

CORS drawback is that IE10 does not support the following, if your project requires a compatible browser, then these need attention.

About CORS agreement Detailed contents look at this article

http://www.ruanyifeng.com/blog/2016/04/cors.html

How to achieve CORS

CORS that white is actually in response headers Riga things, such as nginx you can add in the operation and maintenance aspects of the code may be in Riga, it is common practice middleware centrally. AspNetCore CORS provides middleware for us.

Use AspNetCore_CORS middleware

Use two CORS middleware code that is enough, in the Startup file


//注入CORS相关的服务,配置跨域策略 [CorsPolicy]
public void ConfigureServices(IServiceCollection services)
{
    //策略1,允许所有域名跨域访问
    config.AddPolicy("policy1", policy => {
                    policy.AllowAnyOrigin().
                        AllowAnyMethod().
                        AllowAnyOrigin().
                        AllowAnyMethod();
                        //注意:AllowAnyOrigin和AllowCredential不能同时出现,否则会报错
                        //AllowCredential即是否允许客户端发送cookie,基于安全原因,CORS协议规定不允许AllowOrigin为通配符的情况下设置允许发送cookie
                        //.AllowCredentials();
                });

    //策略2,仅允许特定域名、方法、请求头访问
    config.AddPolicy("policy2",policy=> {
        //只允许https://www.holdengong.com跨域访问
        policy.WithOrigins("https://www.holdengong.com")
        //只允许get,post方法
        .WithMethods("get", "post")
        //请求头中只允许有Authorization
        .WithHeaders("Authorization")
        //对于复杂请求,浏览器会首先发送预检请求(OPTIONS),服务端返回204,并在响应头中返回跨域设置
        //此处可以设置预检请求的有效时长,即30分钟内不会再检查是否允许跨域
        .SetPreflightMaxAge(TimeSpan.FromMinutes(30));
    });
}

//使用CORS中间件, 指定使用CorsPolicy
public void Configure(IApplicationBuilder app)
{
    app.UseCors("CorsPolicy");
}

Note: AllowAnyOrigin and AllowCredential can not be configured, otherwise it will error. If you want to allow the client to send the cookie, it can only be performed using WithOrgin allow cross-domain whitelist

Microsoft's strategy to use design patterns to help us the flexibility to use cross-domain policy. For example, the development environment to allow localhost cross-domain access, easy development and debugging, the official environment only allows you to specify domain names.

Source resolve

Core Objects

services.TryAdd(ServiceDescriptor.Transient<ICorsService, CorsService>());

services.TryAdd(ServiceDescriptor.Transient<ICorsPolicyProvider, DefaultCorsPolicyProvider>());

services.Configure(setupAction);
  • CorsOptions: the main definition dictionary PolicyMap, the key is the policy name, value is the cross-domain policy. Users can go to the object which add cross-domain policy at the time of injection. Then provide some method of operation of the new strategy.
// DefaultCorsPolicyProvider returns a Task<CorsPolicy>. We'll cache the value to be returned alongside
// the actual policy instance to have a separate lookup.
internal IDictionary<string, (CorsPolicy policy, Task<CorsPolicy> policyTask)> PolicyMap { get; }
    = new Dictionary<string, (CorsPolicy, Task<CorsPolicy>)>(StringComparer.Ordinal);
  • ICorsService: There are two ways, EvaluatePolicy-- assessment strategies, mainly to do some checking, recording work logs and split preflight request and the real request; PopulateResult-- execution strategy, will fill the results to CorsResult object.

  • ICorsPolicyProvider: There is a method, GetPolicyAsync-- remove cross-domain policy according policyName.

Middleware

CorsMiddleware

First, the middleware node will determine whether there is a method to achieve the following two interfaces, if any node settings take precedence.

IDisableCorsAttribute: 禁用跨域
ICorsPolicyMetadata:使用指定跨域策略

Then, and then determine whether there is a request header Origin, then no skip directly to a downstream pipe CORS middleware.

if (!context.Request.Headers.ContainsKey(CorsConstants.Origin))
{
return _next(context);
}

Then, the middleware execution ApplyResult method ICorsService will cross-domain policy written response header.

Original Address: holdengong.com

Guess you like

Origin www.cnblogs.com/holdengong/p/12500322.html