【问题标题】:Access-Control-Allow-Origin Ok in this situation?Access-Control-Allow-Origin 在这种情况下好吗?
【发布时间】:2017-12-14 16:21:59
【问题描述】:

我正在关注this tutorial 的某些部分,但我想知道使用“*”是否安全,或者我是否应该将其作为我的域名?

public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {

        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        using (AuthRepository _repo = new AuthRepository())
        {
            IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
        }

        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim("sub", context.UserName));
        identity.AddClaim(new Claim("role", "user"));

        context.Validated(identity);

    }
}

【问题讨论】:

    标签: c# asp.net asp.net-web-api cors


    【解决方案1】:

    这取决于您的具体用例。

    理想情况下,您应该将其限制为尽可能少 - 如果可以,您自己的域(如果有多个域,则为域列表) - 但如果您需要允许对该 API 的公共访问,那么您将拥有允许“*”。

    我还应该指出,您可以在非常精细的基础上设置 CORS 限制 - 例如对于每种方法,如果需要。请参阅下面来自 MS 文档的示例:https://docs.microsoft.com/en-us/aspnet/core/security/cors

    [HttpGet]
    [EnableCors("AllowSpecificOrigin")]
    public IEnumerable<string> Get()
    {
      return new string[] { "value1", "value2" };
    }
    

    【讨论】:

    • 在教程的另一部分他们使用 app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);。它们是相互协作还是相互覆盖?
    • 它们可以一起使用——就像你可以定义一个全局策略,然后通过装饰具有不同要求的特定类/方法来覆盖全局设置。
    • 因此,如果我将其更改为: context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "MyDomain" });那么它会取消 pp.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);.correct?
    • 是的,本地 Cors 设置会覆盖全局设置。见这篇官方 MS 文章:docs.microsoft.com/en-us/aspnet/core/security/cors
    猜你喜欢
    • 2017-06-15
    • 2014-01-28
    • 2016-09-30
    • 2015-06-17
    • 2017-12-29
    • 2019-10-25
    • 2019-02-07
    • 2013-09-09
    相关资源
    最近更新 更多