Updated EnableCorsAttribute and UseCors extension to not have to supply a policy name.

This commit is contained in:
Kiran Challa 2017-09-09 11:47:20 -07:00
parent 370bc7d7c5
commit 5eae687ddd
6 changed files with 186 additions and 1 deletions

View File

@ -11,7 +11,16 @@ namespace Microsoft.AspNetCore.Cors
public class EnableCorsAttribute : Attribute, IEnableCorsAttribute public class EnableCorsAttribute : Attribute, IEnableCorsAttribute
{ {
/// <summary> /// <summary>
/// Creates a new instance of the <see cref="EnableCorsAttribute"/>. /// Creates a new instance of the <see cref="EnableCorsAttribute"/> with the default policy
/// name defined by <see cref="CorsOptions.DefaultPolicyName"/>.
/// </summary>
public EnableCorsAttribute()
: this(policyName: null)
{
}
/// <summary>
/// Creates a new instance of the <see cref="EnableCorsAttribute"/> with the supplied policy name.
/// </summary> /// </summary>
/// <param name="policyName">The name of the policy to be applied.</param> /// <param name="policyName">The name of the policy to be applied.</param>
public EnableCorsAttribute(string policyName) public EnableCorsAttribute(string policyName)

View File

@ -19,6 +19,20 @@ namespace Microsoft.AspNetCore.Cors.Infrastructure
private readonly CorsPolicy _policy; private readonly CorsPolicy _policy;
private readonly string _corsPolicyName; private readonly string _corsPolicyName;
/// <summary>
/// Instantiates a new <see cref="CorsMiddleware"/>.
/// </summary>
/// <param name="next">The next middleware in the pipeline.</param>
/// <param name="corsService">An instance of <see cref="ICorsService"/>.</param>
/// <param name="policyProvider">A policy provider which can get an <see cref="CorsPolicy"/>.</param>
public CorsMiddleware(
RequestDelegate next,
ICorsService corsService,
ICorsPolicyProvider policyProvider)
: this(next, corsService, policyProvider, policyName: null)
{
}
/// <summary> /// <summary>
/// Instantiates a new <see cref="CorsMiddleware"/>. /// Instantiates a new <see cref="CorsMiddleware"/>.
/// </summary> /// </summary>

View File

@ -11,6 +11,21 @@ namespace Microsoft.AspNetCore.Builder
/// </summary> /// </summary>
public static class CorsMiddlewareExtensions public static class CorsMiddlewareExtensions
{ {
/// <summary>
/// Adds a CORS middleware to your web application pipeline to allow cross domain requests.
/// </summary>
/// <param name="app">The IApplicationBuilder passed to your Configure method</param>
/// <returns>The original app parameter</returns>
public static IApplicationBuilder UseCors(this IApplicationBuilder app)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
return app.UseMiddleware<CorsMiddleware>();
}
/// <summary> /// <summary>
/// Adds a CORS middleware to your web application pipeline to allow cross domain requests. /// Adds a CORS middleware to your web application pipeline to allow cross domain requests.
/// </summary> /// </summary>

View File

@ -31,6 +31,34 @@ namespace Microsoft.AspNetCore.Cors.Infrastructure
} }
} }
/// <summary>
/// Adds a new policy and sets it as the default.
/// </summary>
/// <param name="policy">The <see cref="CorsPolicy"/> policy to be added.</param>
public void AddDefaultPolicy(CorsPolicy policy)
{
if (policy == null)
{
throw new ArgumentNullException(nameof(policy));
}
AddPolicy(DefaultPolicyName, policy);
}
/// <summary>
/// Adds a new policy and sets it as the default.
/// </summary>
/// <param name="configurePolicy">A delegate which can use a policy builder to build a policy.</param>
public void AddDefaultPolicy(Action<CorsPolicyBuilder> configurePolicy)
{
if (configurePolicy == null)
{
throw new ArgumentNullException(nameof(configurePolicy));
}
AddPolicy(DefaultPolicyName, configurePolicy);
}
/// <summary> /// <summary>
/// Adds a new policy. /// Adds a new policy.
/// </summary> /// </summary>

View File

@ -297,5 +297,57 @@ namespace Microsoft.AspNetCore.Cors.Infrastructure
o => o.GetPolicyAsync(It.IsAny<HttpContext>(), It.IsAny<string>()), o => o.GetPolicyAsync(It.IsAny<HttpContext>(), It.IsAny<string>()),
Times.Once); Times.Once);
} }
[Fact]
public async Task PreFlight_MatchesDefaultPolicy_SetsResponseHeaders()
{
// Arrange
var hostBuilder = new WebHostBuilder()
.Configure(app =>
{
app.UseCors();
app.Run(async context =>
{
await context.Response.WriteAsync("Cross origin response");
});
})
.ConfigureServices(services =>
{
services.AddCors(options =>
{
options.AddDefaultPolicy(policyBuilder =>
{
policyBuilder
.WithOrigins("http://localhost:5001")
.WithMethods("PUT")
.WithHeaders("Header1")
.WithExposedHeaders("AllowedHeader")
.Build();
});
options.AddPolicy("policy2", policyBuilder =>
{
policyBuilder
.WithOrigins("http://localhost:5002")
.Build();
});
});
});
using (var server = new TestServer(hostBuilder))
{
// Act
// Preflight request.
var response = await server.CreateRequest("/")
.AddHeader(CorsConstants.Origin, "http://localhost:5001")
.AddHeader(CorsConstants.AccessControlRequestMethod, "PUT")
.SendAsync(CorsConstants.PreflightHttpMethod);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(2, response.Headers.Count());
Assert.Equal("http://localhost:5001", response.Headers.GetValues(CorsConstants.AccessControlAllowOrigin).FirstOrDefault());
Assert.Equal("PUT", response.Headers.GetValues(CorsConstants.AccessControlAllowMethods).FirstOrDefault());
}
}
} }
} }

View File

@ -0,0 +1,67 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Xunit;
namespace Microsoft.AspNetCore.Cors.Infrastructure
{
public class CorsOptionsTest
{
[Fact]
public void AddDefaultPolicy_SetsDefaultPolicyName()
{
// Arrange
var corsOptions = new CorsOptions();
var expectedPolicy = new CorsPolicy();
// Act
corsOptions.AddPolicy("policy1", new CorsPolicy());
corsOptions.AddDefaultPolicy(expectedPolicy);
corsOptions.AddPolicy("policy3", new CorsPolicy());
// Assert
var actualPolicy = corsOptions.GetPolicy(corsOptions.DefaultPolicyName);
Assert.Same(expectedPolicy, actualPolicy);
}
[Fact]
public void AddDefaultPolicy_OverridesDefaultPolicyName()
{
// Arrange
var corsOptions = new CorsOptions();
var expectedPolicy = new CorsPolicy();
// Act
corsOptions.AddDefaultPolicy(new CorsPolicy());
corsOptions.AddDefaultPolicy(expectedPolicy);
// Assert
var actualPolicy = corsOptions.GetPolicy(corsOptions.DefaultPolicyName);
Assert.Same(expectedPolicy, actualPolicy);
}
[Fact]
public void AddDefaultPolicy_UsingPolicyBuilder_SetsDefaultPolicyName()
{
// Arrange
var corsOptions = new CorsOptions();
CorsPolicy expectedPolicy = null;
// Act
corsOptions.AddPolicy("policy1", policyBuilder =>
{
policyBuilder.AllowAnyOrigin().Build();
});
corsOptions.AddDefaultPolicy(policyBuilder =>
{
expectedPolicy = policyBuilder.AllowAnyOrigin().Build();
});
corsOptions.AddPolicy("policy3", new CorsPolicy());
// Assert
var actualPolicy = corsOptions.GetPolicy(corsOptions.DefaultPolicyName);
Assert.Same(expectedPolicy, actualPolicy);
}
}
}