JWT身份验证

时间:2016-05-24 08:15:48

标签: asp.net-core jwt

我的团队正在.net核心构建一个web api。我们使用令牌身份验证来验证任何客户端,该令牌来自Azure AD。

我们将此代码放在Startup.cs

app.UseJwtBearerAuthentication(options => {
            options.AutomaticAuthenticate = true;
            options.AutomaticChallenge = true;               
            options.Authority = "https://login.windows.net/1da3434a9-e5a6-4e9e-80c3-aca8ed37cb03";               
            options.Audience = "https://test.onmicrosoft.com/test_api";
            options.RequireHttpsMetadata = false;
        });

        services.AddCors(options =>
        {
            // Define one or more CORS policies
            options.AddPolicy("AllowAll",
                builder =>
                {
                    builder.AllowAnyOrigin()
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials();
                });
        });

这个只在我们允许匿名访问时才有用。我检查了令牌,令牌有效。但是每次我们击中控制器都会引起cors错误。即使我们启用了角色

2 个答案:

答案 0 :(得分:0)

添加中间件的顺序很重要!

  

要为整个应用程序启用CORS,请将CORS中间件添加到   您的请求管道使用UseCors扩展方法。注意   CORS中间件必须在您的应用程序中继续任何已定义的端点   您希望支持跨源请求(例如,在调用之前)   UseMvc)。

您应该将services.AddCors放在几乎所有可能通过401重定向用户的内容之上。

答案 1 :(得分:0)

您无法合并AllowCredentials& AllowAnyOrigin。选择一个特定的来源,您的请求可能会有效。